SQL Query Cheat Sheet
Quick reference for common SQL query patterns.
Basic SELECT
Section titled “Basic SELECT”SELECT * FROM employees # All columnsSELECT first_name, last_name FROM employees # Specific columnsSELECT DISTINCT department_id FROM employees # Unique values onlySELECT TOP 10 * FROM employees # First 10 rowsSELECT first_name AS name FROM employees # Rename columnWHERE: Filtering
Section titled “WHERE: Filtering”SELECT * FROM employees WHERE salary > 50000SELECT * FROM employees WHERE last_name = 'Smith'SELECT * FROM employees WHERE hire_date > '2020-01-01'SELECT * FROM employees WHERE outservice_date IS NULL # No valueSELECT * FROM employees WHERE outservice_date IS NOT NULL # Has valueComparison Operators
Section titled “Comparison Operators”= (equal) !=, <> (not equal) < (less than)<= (less or equal) > (greater than) >= (greater or equal)BETWEEN IN LIKE (pattern match)IS NULL IS NOT NULLLogical Operators
Section titled “Logical Operators”WHERE salary > 50000 AND department_id = 10 # Both trueWHERE status = 'Active' OR status = 'Pending' # At least one trueWHERE NOT status = 'Inactive' # Reverse conditionIN: Multiple Values
Section titled “IN: Multiple Values”SELECT * FROM employeesWHERE department_id IN (10, 20, 30) # Any of these valuesBETWEEN: Range
Section titled “BETWEEN: Range”SELECT * FROM employeesWHERE salary BETWEEN 40000 AND 60000 # 40k to 60k inclusiveWHERE hire_date BETWEEN '2020-01-01' AND '2023-12-31'LIKE: Pattern Matching
Section titled “LIKE: Pattern Matching”SELECT * FROM employees WHERE first_name LIKE 'J%' # Starts with JSELECT * FROM employees WHERE last_name LIKE '%son' # Ends with sonSELECT * FROM employees WHERE email LIKE '%@%' # Contains @SELECT * FROM employees WHERE first_name LIKE '_oh_' # ? wildcardORDER BY: Sorting
Section titled “ORDER BY: Sorting”SELECT * FROM employees ORDER BY last_name # A-ZSELECT * FROM employees ORDER BY salary DESC # Highest firstSELECT * FROM employees ORDER BY department_id ASC, salary DESC # Multi-columnCOUNT: Counting Rows
Section titled “COUNT: Counting Rows”SELECT COUNT(*) FROM employees # Total employeesSELECT COUNT(DISTINCT department_id) FROM employees # Unique departmentsSUM, AVG, MIN, MAX: Aggregates
Section titled “SUM, AVG, MIN, MAX: Aggregates”SELECT SUM(salary) FROM employees # Total salarySELECT AVG(salary) FROM employees # Average salarySELECT MIN(salary) FROM employees # Lowest salarySELECT MAX(salary) FROM employees # Highest salaryGROUP BY: Grouping
Section titled “GROUP BY: Grouping”SELECT department_id, COUNT(*) as countFROM employeesGROUP BY department_id # Count per department
SELECT department_id, AVG(salary) as avg_salaryFROM employeesGROUP BY department_idHAVING: Filtering Groups
Section titled “HAVING: Filtering Groups”SELECT department_id, COUNT(*) as countFROM employeesGROUP BY department_idHAVING COUNT(*) > 5 # Only groups with >5 employeesJOIN: Combining Tables
Section titled “JOIN: Combining Tables”SELECT e.first_name, d.department_nameFROM employees eJOIN departments d ON e.department_id = d.department_id
SELECT e.first_name, e.last_name, l.cityFROM employees eJOIN departments d ON e.department_id = d.department_idJOIN locations l ON d.location_id = l.location_idLEFT JOIN: Keep All Left Table Rows
Section titled “LEFT JOIN: Keep All Left Table Rows”SELECT e.first_name, d.department_nameFROM employees eLEFT JOIN departments d ON e.department_id = d.department_id# Shows all employees, even if department doesn't existINNER JOIN vs LEFT JOIN
Section titled “INNER JOIN vs LEFT JOIN”INNER JOIN # Only rows that match both tablesLEFT JOIN # All rows from left table, matching rows from rightINSERT: Adding Data
Section titled “INSERT: Adding Data”INSERT INTO employees (first_name, last_name, salary)VALUES ('John', 'Doe', 55000)
INSERT INTO employees (first_name, last_name, salary)VALUES('Alice', 'Smith', 60000),('Bob', 'Johnson', 58000) # Multiple rowsUPDATE: Changing Data
Section titled “UPDATE: Changing Data”UPDATE employeesSET salary = 62000WHERE employee_id = 101
UPDATE employeesSET salary = 65000, department_id = 20WHERE first_name = 'John'DELETE: Removing Data
Section titled “DELETE: Removing Data”DELETE FROM employeesWHERE employee_id = 101
DELETE FROM employeesWHERE hire_date < '2010-01-01' # Delete old employeesCREATE TABLE
Section titled “CREATE TABLE”CREATE TABLE employees ( employee_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(100), salary DECIMAL(10,2), hire_date DATE)ALTER TABLE: Modifying Tables
Section titled “ALTER TABLE: Modifying Tables”ALTER TABLE employeesADD phone_number VARCHAR(30) # Add column
ALTER TABLE employeesDROP COLUMN phone_number # Remove column
ALTER TABLE employeesADD CONSTRAINT fk_deptFOREIGN KEY (department_id) REFERENCES departments(department_id)CREATE INDEX
Section titled “CREATE INDEX”CREATE INDEX idx_lastname ON employees(last_name) # Faster searchesCREATE INDEX idx_multi ON employees(department_id, salary)UNION: Combining Results
Section titled “UNION: Combining Results”SELECT first_name FROM employeesUNIONSELECT first_name FROM dependents # Combine results, remove duplicates
SELECT first_name FROM employeesUNION ALLSELECT first_name FROM dependents # Include duplicatesCASE: Conditional Values
Section titled “CASE: Conditional Values”SELECT first_name,CASE WHEN salary > 60000 THEN 'High' WHEN salary > 50000 THEN 'Medium' ELSE 'Low'END as salary_levelFROM employeesString Functions
Section titled “String Functions”CONCAT(first_name, ' ', last_name) # Combine stringsUPPER(first_name) # UppercaseLOWER(first_name) # LowercaseLEN(first_name) # String lengthSUBSTRING(email, 1, 5) # Extract charactersREPLACE(email, '@old.com', '@new.com') # Find and replaceDate Functions
Section titled “Date Functions”GETDATE() # Current date/timeDATEDIFF(day, hire_date, '2024-01-01') # Days between datesDATEADD(month, 6, hire_date) # Add days/months/yearsYEAR(hire_date) # Extract yearMONTH(hire_date) # Extract monthDAY(hire_date) # Extract dayDISTINCT: Unique Values
Section titled “DISTINCT: Unique Values”SELECT DISTINCT city FROM locations # One row per unique cityLIMIT/TOP: Restrict Results
Section titled “LIMIT/TOP: Restrict Results”SELECT TOP 5 * FROM employees # First 5 rows (SQL Server)SELECT * FROM employees LIMIT 5 # First 5 rows (MySQL)ORDER BY with LIMIT
Section titled “ORDER BY with LIMIT”SELECT TOP 10 *FROM employeesORDER BY salary DESC # Top 10 highest paidAliases in Aggregates
Section titled “Aliases in Aggregates”SELECT department_id, COUNT(*) as total_employees, AVG(salary) as average_salaryFROM employeesGROUP BY department_idComments
Section titled “Comments”-- Single line comment
/* Multi-line comment explains complex queries */NULL Handling
Section titled “NULL Handling”SELECT first_name, ISNULL(phone_number, 'No phone') # Use default if NULLSELECT first_name WHERE phone_number IS NOT NULL # Only rows with value