SQL Cheat Sheet
SELECT, WHERE, NULL, functions, CASE, GROUP BY, dates, JOIN, UNION, CTEs, views, indexes, transactions, window functions, triggers and security on one printable page.
Reading data
| Syntax | What it does | Lesson |
|---|---|---|
SELECT * FROM t; | Every column and row | Introduction |
SELECT a, b FROM t; | Only some columns | SELECT |
SELECT a AS label | Rename a column in the result | SELECT |
SELECT DISTINCT city | Remove duplicates | SELECT |
Filtering
Functions & CASE
| Syntax | What it does | Lesson |
|---|---|---|
UPPER(x) LOWER(x) LENGTH(x) | Text functions | Functions |
SUBSTR(x, 1, 3) TRIM(x) | Part of text, trim spaces | Functions |
a || ' ' || b | Join text (CONCAT in MySQL) | Functions |
ROUND(x, 2) ABS(x) | Number functions | Functions |
COALESCE(x, 'n/a') | Fallback for NULL | Functions |
CASE WHEN c THEN a ELSE b END | If-then-else in a query | CASE |
Sorting & summarising
Changing data
| Syntax | What it does | Lesson |
|---|---|---|
INSERT INTO t (a, b) VALUES (1, 'x'); | Add a row | INSERT |
UPDATE t SET a = 2 WHERE id = 1; | Change rows | UPDATE |
DELETE FROM t WHERE id = 1; | Remove rows | DELETE |
BEGIN; COMMIT; ROLLBACK; | All-or-nothing changes | Transactions |
Tables & constraints
| Syntax | What it does | Lesson |
|---|---|---|
CREATE TABLE t (id INTEGER PRIMARY KEY, ...) | Create a table | CREATE TABLE |
ALTER TABLE t ADD COLUMN c TEXT; | Add a column | CREATE TABLE |
DROP TABLE IF EXISTS t; | Delete a table | CREATE TABLE |
NOT NULL UNIQUE DEFAULT 0 | Column rules | Constraints |
CHECK (qty > 0) | Reject bad values | Constraints |
REFERENCES customers(id) | Foreign key | Constraints |
Joins & subqueries
| Syntax | What it does | Lesson |
|---|---|---|
JOIN c ON o.customer_id = c.id | Matching rows only | JOIN |
LEFT JOIN o ON o.customer_id = c.id | Keep every left row | JOIN |
WHERE x > (SELECT AVG(x) FROM t) | Scalar subquery | Subqueries |
WHERE EXISTS (SELECT 1 FROM ...) | Related rows exist? | Subqueries |
WITH name AS (SELECT ...) | Common table expression | Subqueries |
Views, indexes & windows
| Syntax | What it does | Lesson |
|---|---|---|
CREATE VIEW v AS SELECT ...; | Save a query | Views |
CREATE INDEX i ON t (col); | Faster lookups | Indexes |
EXPLAIN QUERY PLAN SELECT ... | See how a query runs | Indexes |
ROW_NUMBER() OVER (ORDER BY x) | Number rows | Window functions |
RANK() OVER (PARTITION BY g ORDER BY x) | Rank within groups | Window functions |
SUM(x) OVER (ORDER BY d) | Running total | Window functions |
NULL & dates
| Syntax | What it does | Lesson |
|---|---|---|
WHERE col IS NULL | Find missing values | NULL Values |
COALESCE(col, 'n/a') | Replace NULL with a default | NULL Values |
COUNT(col) vs COUNT(*) | Skip NULLs / count every row | NULL Values |
WHERE d >= '2024-07-01' AND d < '2024-08-01' | A safe date range | Dates & Times |
strftime('%Y-%m', d) | Year and month (SQLite) | Dates & Times |
date(d, '+7 days') | Add days (SQLite) | Dates & Times |
julianday(b) - julianday(a) | Days between (SQLite) | Dates & Times |
More joins & set operations
| Syntax | What it does | Lesson |
|---|---|---|
LEFT JOIN b ... WHERE b.id IS NULL | Rows with no match | More Joins |
FROM staff e JOIN staff m ON m.id = e.manager_id | Self join | More Joins |
FULL OUTER JOIN | All rows from both tables | More Joins |
CROSS JOIN | Every combination | More Joins |
UNION / UNION ALL | Stack results, with or without duplicates | UNION |
INTERSECT / EXCEPT | In both / in first only | UNION |
Cleaning & design
| Syntax | What it does | Lesson |
|---|---|---|
TRIM(col) LOWER(col) | Standardise text | Data Cleaning |
GROUP BY key HAVING COUNT(*) > 1 | Find duplicates | Data Cleaning |
NULLIF(TRIM(col), '') | Blank to NULL | Data Cleaning |
PRIMARY KEY (a_id, b_id) | Junction table key | Relationships |
REFERENCES t(id) ON DELETE CASCADE | Delete linked rows too | Relationships |
| 1NF, 2NF, 3NF | Store each fact once | Normalization |
CTEs, triggers & security
| Syntax | What it does | Lesson |
|---|---|---|
WITH a AS (...), b AS (...) SELECT ... | Named query steps | CTEs |
WITH RECURSIVE r AS (anchor UNION ALL ...) | Series and hierarchies | CTEs |
CREATE TRIGGER t AFTER UPDATE ON tbl | Run SQL on data changes | Triggers & Procedures |
OLD.col / NEW.col | Values before / after | Triggers & Procedures |
CALL procedure(1) | Run a stored procedure | Triggers & Procedures |
WHERE email = ? | Parameterized query | Security |
GRANT SELECT ON t TO user | Give a privilege | Security |
REVOKE INSERT ON t FROM user | Remove a privilege | Security |
How to use this SQL cheat sheet
This SQL cheat sheet gathers the statements and clauses you'll use most, in the same order as the course: reading data, filtering and NULL, functions and CASE, sorting and summarising, changing data, dates, creating tables and constraints, joins and UNION, subqueries and CTEs, data cleaning, views, indexes, transactions, window functions, triggers and security. Each row links to the lesson that explains it properly, with example results from the course's shop database and the mistakes to avoid.
Keep it open while you practise in SQLite, MySQL or PostgreSQL. Where the three databases spell something differently, such as auto-numbered ids, joining text or date functions, the linked lesson shows each version. Type a keyword such as "JOIN" or "LIKE" into the filter box to find a row instantly, or print the page for a one-sheet reference next to your keyboard. Remember the order of clauses, too: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
SQL gotchas worth remembering
- NULL is never equal to anything.
WHERE phone = NULLmatches no rows. UseIS NULLandIS NOT NULL. - WHERE filters rows, HAVING filters groups. You can't use an aggregate such as
COUNT(*)in WHERE; move that condition to HAVING. - Every selected column must be grouped. With GROUP BY, each column in SELECT must either be in the GROUP BY or inside an aggregate.
- Forgetting WHERE in UPDATE or DELETE changes every row. Run the same WHERE with SELECT first, and use a transaction when in doubt.
- LEFT JOIN conditions belong in ON. Putting a condition on the right-hand table in WHERE quietly turns it back into an inner join.
Practise each pattern on a small table of your own, then confirm with the SQL quiz.
The SQL lessons behind this cheat sheet
Beginner
Intermediate
Advanced
Syntax and commands reference
- 26SQL Syntax and Comments: A Clear Beginner Reference
- 27SQL Operators and Precedence: AND, OR and Parentheses
- 28SQL SELECT DISTINCT: Remove Duplicates Correctly
- 29SQL Column and Table Aliases: AS and Qualified Names
- 30SQL LIKE and Wildcards: Percent, Underscore and Escaping
- 31SQL IN, BETWEEN, ANY and ALL: Comparison Reference
- 32SQL EXISTS and NOT EXISTS: Check Related Rows Safely
- 33SQL IS NULL and IS NOT NULL: Find Missing Values
- 34SQL LIMIT, TOP and FETCH FIRST: Select the First Rows
- 35SQL Keywords and Commands: SELECT, DDL, DML and Transactions
Functions and querying reference
- 36SQL MIN Function: Find the Smallest Value with Examples
- 37SQL MAX Function: Largest Values, Dates and Grouped Results
- 38SQL COUNT: COUNT(*), COUNT(Column) and COUNT DISTINCT
- 39SQL SUM Function: Totals, NULL and Duplicate Rows
- 40SQL AVG Function: Averages, NULL Values and Weighted Means
- 41Aggregate vs Window Functions in SQL: Rows and Groups
- 42SQL GROUP BY and HAVING: Advanced Grouping Examples
- 43SQL String Functions: LOWER, UPPER, TRIM and Substrings
- 44SQL Numeric and Math Functions: ROUND, ABS and Division
- 45SQL Date and Time Functions: Ranges, Parts and Time Zones
- 46SQL COALESCE and NULLIF: Practical NULL Handling
- 47SQL Conditional Aggregation: SUM CASE and COUNT CASE
- 48SQL CAST and CONVERT: Types, Precision and Safe Conversion
- 49SQL ORDER BY Multiple Columns and NULL Values
Database and table reference
- 50SQL CREATE DATABASE and DROP DATABASE: Dialect Guide
- 51SQL CREATE TABLE, ALTER TABLE and DROP TABLE
- 52SQL Data Types: Integers, Decimal, Text, Dates and Boolean
- 53SQL INSERT INTO SELECT: Copy and Transform Query Results
- 54SQL SELECT INTO: New Tables vs Variables by Dialect
- 55SQL DEFAULT, CHECK and UNIQUE Constraints with Examples
- 56SQL AUTO_INCREMENT and Identity Columns: Generated IDs
- 57SQL Primary Keys and Composite Keys: Design and Examples
- 58SQL Foreign Keys: Referential Integrity, CASCADE and SET NULL
- 59SQL Temporary Tables: Scope, Lifetime and Practical Examples
- 60SQL Database Schema and Metadata: Inspect Tables and Columns
Joins and advanced queries reference
- 61SQL INNER JOIN: Matching Rows, Keys and Duplicate Results
- 62SQL LEFT, RIGHT and FULL OUTER JOIN: Unmatched Rows
- 63SQL Self Joins and CROSS JOIN: Roles and Combinations
- 64SQL Anti-Joins: Find Unmatched Rows with NOT EXISTS
- 65SQL UNION vs UNION ALL: Duplicates, Types and Ordering
- 66SQL INTERSECT and EXCEPT: Shared and Missing Set Values
- 67SQL Correlated Subqueries: Outer Rows and Scalar Results
- 68SQL Derived Tables: Subqueries in FROM and Preaggregation
- 69SQL Common Table Expressions: WITH, Scope and Chaining
- 70SQL Recursive Queries: Hierarchies, Depth and Termination
- 71SQL Pivoting with CASE: Turn Categories into Columns
Windows and performance reference
- 72SQL ROW_NUMBER, RANK and DENSE_RANK
- 73SQL LAG and LEAD
- 74SQL Running Totals and Moving Averages
- 75SQL Window Frames and PARTITION BY
- 76SQL Index Types and Composite Indexes
- 77SQL Query Execution Plans with EXPLAIN
- 78SQL Query Optimization and Index Selection
- 79SQL ACID Properties and Transaction Isolation
- 80SQL Deadlocks and Locking
- 81SQL Stored Procedures vs Functions
- 82SQL Triggers and Their Use Cases
Practical SQL
- 83Database Design from Requirements
- 84Entity-Relationship (ER) Diagrams
- 85One-to-One, One-to-Many and Many-to-Many Relationships
- 86Normalization: 1NF, 2NF, 3NF and BCNF
- 87Data Integrity and Referential Integrity
- 88SQL Data Cleaning and Deduplication
- 89Importing and Exporting CSV Data
- 90Database Backup and Restore Basics
- 91SQL Security, Roles and Permissions
- 92Parameterized Queries and SQL Injection Prevention
Dialects and SQL practice
- 93MySQL Tutorial for Beginners with a Small Inventory Database
- 94PostgreSQL Tutorial for Beginners: Projects and Time Entries
- 95SQL Server and T-SQL Basics: Build an Invoice Report
- 96SQLite Tutorial for Beginners: A Reading-List Database
- 97SQL Dialect Differences: Translate Queries Without Changing Their Meaning
- 98SQL Interview Questions with Clear Answers and Query Examples
- 99SQL Coding Challenges with Test Data and Worked Solutions
- 100SQL Exercises by Difficulty with Complete Worked Answers
- 101Real-World Business SQL Problems: Paid Orders, Refunds and Net Value
- 102SQL Reporting and Analytics Projects: Build a Daily Activity Report