SQL Notes
SQL Notes
Basic Commands
SELECT Statements
● SELECT: Used to select data from a database. The data returned is stored in a result table, sometimes
called the result set.
WHERE Clause
Filters records based on a condition.
ORDER BY Clause
Sorts the result set in ascending (ASC) or descending (DESC) order.
LIMIT Clause
Limits the number of records returned.
●
AND, OR, and NOT Operators
Used with WHERE to filter records based on more than one condition.
2. Aggregate Functions
COUNT(): Returns the number of rows.
●
3. Joins
INNER JOIN
Returns records with matching values in both tables.
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
SELECT columns
FROM table1
FULL OUTER JOIN table2
ON table1.column = table2.column;
●
4. Aliases
Used to rename a table or column temporarily.
INSERT INTO
Inserts new data into a table.
UPDATE
Modifies existing records.
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
DELETE
Deletes records.
CREATE TABLE
Creates a new table.
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...
);
ALTER TABLE
Modifies a table’s structure.
DROP TABLE
Deletes a table and all its data.
TRUNCATE TABLE
Deletes all records but keeps the table structure.
7. Constraints
PRIMARY KEY: Uniquely identifies each record.
8. Subqueries
A query within a query, often nested in WHERE or FROM clauses.
SELECT column1
FROM table_name
WHERE column1 IN (SELECT column1 FROM table_name WHERE condition);
9. CASE Statements
Allows conditional logic in .
SELECT column1,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END AS alias_name
FROM table_name;
10. Views
A virtual table based on the result-set of a query.
Modifying Views