SQL Cheatsheet
SQL Cheatsheet
SELECT name, age FROM employees WHERE age > 30 ORDER BY age DESC LIMIT 5;
2. Aggregate Functions
● COUNT(): Counts the number of rows.
● SUM(): Adds up values.
● AVG(): Calculates average value.
● MAX()/MIN(): Finds highest/lowest value.
WITH HighEarners AS (SELECT name, salary FROM employees WHERE salary > 80000)
SELECT * FROM HighEarners;
6. Window Functions
● Perform calculations across rows related to current row (without GROUP BY).
● RANK(): Rank of rows.
● LAG()/LEAD(): Access previous/next row data.
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) FROM employees;
7. Constraints
Rules applied to table columns to enforce data integrity:
CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, salary
DECIMAL(10,2) CHECK (salary > 0));
9. Transactions
● Set of SQL operations that are atomic (all succeed or all fail).
● BEGIN TRANSACTION: Start.
● COMMIT: Save changes.
● ROLLBACK: Undo changes if error occurs.
BEGIN TRANSACTION;
COMMIT;