SQL commands are the building blocks that enable you to retrieve, manipulate, and maintain data within databases efficiently. In this beginner's guide, I'll take you on a journey through the fundamental SQL commands.
SELECT Statement:
SELECT column1, column2
FROM table_name
WHERE condition;
FROM table_name
WHERE condition;
SELECT Statement (with aliases):
SELECT column1 AS alias1, column2 AS alias2
FROM table_name
WHERE condition;
SELECT Statement (with ORDER BY):
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC, column2 DESC;
INSERT Statement:
INSERT INTO table_name (column1, column2)
VALUES (value1, value2);
UPDATE Statement:
UPDATE table_name
SET column1 = new_value
WHERE condition;
DELETE Statement:
DELETE FROM table_name
WHERE condition;
JOIN Clause (INNER JOIN):
SELECT columns
FROM table1
INNER JOIN table2 ON table1.column = table2.column;
JOIN Clause (LEFT JOIN):
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
GROUP BY Clause:
SELECT column, COUNT(*)
FROM table_name
GROUP BY column;
HAVING Clause:
SELECT column, COUNT(*)
FROM table_name
GROUP BY column
HAVING COUNT(*) > 1;
Subqueries:
SELECT column
FROM table_name
WHERE column IN (SELECT column FROM another_table);
CASE Statement:
SELECT column,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END AS alias
FROM table_name;
CREATE TABLE Statement:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...
);
ALTER TABLE Statement (Add Column):
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE Statement (Modify Column):
ALTER TABLE table_name
MODIFY column_name new_datatype;
DROP TABLE Statement:
DROP TABLE table_name;
Basic SQL Functions:
- COUNT(): Count the number of rows.
- SUM(): Calculate the sum of values in a column.
- AVG(): Calculate the average of values in a column.
- MIN(): Find the minimum value in a column.
- MAX(): Find the maximum value in a column.
JOIN Clause (INNER JOIN):
SELECT columns
FROM table1
INNER JOIN table2 ON table1.column = table2.column;
JOIN Clause (LEFT JOIN):
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
GROUP BY Clause:
SELECT column, COUNT(*)
FROM table_name
GROUP BY column;
HAVING Clause:
SELECT column, COUNT(*)
FROM table_name
GROUP BY column
HAVING COUNT(*) > 1;
Subqueries:
SELECT column
FROM table_name
WHERE column IN (SELECT column FROM another_table);
CASE Statement:
SELECT column,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END AS alias
FROM table_name;
0 Comments