SQLPrintable

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.

Back to the SQL tutorial

Reading data

SyntaxWhat it doesLesson
SELECT * FROM t;Every column and rowIntroduction
SELECT a, b FROM t;Only some columnsSELECT
SELECT a AS labelRename a column in the resultSELECT
SELECT DISTINCT cityRemove duplicatesSELECT

Filtering

SyntaxWhat it doesLesson
WHERE price > 10Compare: = <> > < >= <=WHERE
WHERE a = 1 AND (b = 2 OR c = 3)Combine conditionsWHERE
WHERE city IN ('A', 'B')Match a listWHERE
WHERE n BETWEEN 1 AND 9Inclusive rangeWHERE
WHERE name LIKE 'A%'Pattern: % any, _ one charWHERE
WHERE city IS NULLMissing valueWHERE

Functions & CASE

SyntaxWhat it doesLesson
UPPER(x) LOWER(x) LENGTH(x)Text functionsFunctions
SUBSTR(x, 1, 3) TRIM(x)Part of text, trim spacesFunctions
a || ' ' || bJoin text (CONCAT in MySQL)Functions
ROUND(x, 2) ABS(x)Number functionsFunctions
COALESCE(x, 'n/a')Fallback for NULLFunctions
CASE WHEN c THEN a ELSE b ENDIf-then-else in a queryCASE

Sorting & summarising

SyntaxWhat it doesLesson
ORDER BY price DESCSort (ASC is default)ORDER BY
LIMIT 5First 5 rowsORDER BY
COUNT(*) SUM(x) AVG(x)Count, total, averageORDER BY
GROUP BY categoryOne row per groupORDER BY
HAVING COUNT(*) > 1Filter groupsORDER BY
SUM(CASE WHEN c THEN 1 ELSE 0 END)Conditional countCASE

Changing data

SyntaxWhat it doesLesson
INSERT INTO t (a, b) VALUES (1, 'x');Add a rowINSERT
UPDATE t SET a = 2 WHERE id = 1;Change rowsUPDATE
DELETE FROM t WHERE id = 1;Remove rowsDELETE
BEGIN; COMMIT; ROLLBACK;All-or-nothing changesTransactions

Tables & constraints

SyntaxWhat it doesLesson
CREATE TABLE t (id INTEGER PRIMARY KEY, ...)Create a tableCREATE TABLE
ALTER TABLE t ADD COLUMN c TEXT;Add a columnCREATE TABLE
DROP TABLE IF EXISTS t;Delete a tableCREATE TABLE
NOT NULL UNIQUE DEFAULT 0Column rulesConstraints
CHECK (qty > 0)Reject bad valuesConstraints
REFERENCES customers(id)Foreign keyConstraints

Joins & subqueries

SyntaxWhat it doesLesson
JOIN c ON o.customer_id = c.idMatching rows onlyJOIN
LEFT JOIN o ON o.customer_id = c.idKeep every left rowJOIN
WHERE x > (SELECT AVG(x) FROM t)Scalar subquerySubqueries
WHERE EXISTS (SELECT 1 FROM ...)Related rows exist?Subqueries
WITH name AS (SELECT ...)Common table expressionSubqueries

Views, indexes & windows

SyntaxWhat it doesLesson
CREATE VIEW v AS SELECT ...;Save a queryViews
CREATE INDEX i ON t (col);Faster lookupsIndexes
EXPLAIN QUERY PLAN SELECT ...See how a query runsIndexes
ROW_NUMBER() OVER (ORDER BY x)Number rowsWindow functions
RANK() OVER (PARTITION BY g ORDER BY x)Rank within groupsWindow functions
SUM(x) OVER (ORDER BY d)Running totalWindow functions

NULL & dates

SyntaxWhat it doesLesson
WHERE col IS NULLFind missing valuesNULL Values
COALESCE(col, 'n/a')Replace NULL with a defaultNULL Values
COUNT(col) vs COUNT(*)Skip NULLs / count every rowNULL Values
WHERE d >= '2024-07-01' AND d < '2024-08-01'A safe date rangeDates & 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

SyntaxWhat it doesLesson
LEFT JOIN b ... WHERE b.id IS NULLRows with no matchMore Joins
FROM staff e JOIN staff m ON m.id = e.manager_idSelf joinMore Joins
FULL OUTER JOINAll rows from both tablesMore Joins
CROSS JOINEvery combinationMore Joins
UNION / UNION ALLStack results, with or without duplicatesUNION
INTERSECT / EXCEPTIn both / in first onlyUNION

Cleaning & design

SyntaxWhat it doesLesson
TRIM(col) LOWER(col)Standardise textData Cleaning
GROUP BY key HAVING COUNT(*) > 1Find duplicatesData Cleaning
NULLIF(TRIM(col), '')Blank to NULLData Cleaning
PRIMARY KEY (a_id, b_id)Junction table keyRelationships
REFERENCES t(id) ON DELETE CASCADEDelete linked rows tooRelationships
1NF, 2NF, 3NFStore each fact onceNormalization

CTEs, triggers & security

SyntaxWhat it doesLesson
WITH a AS (...), b AS (...) SELECT ...Named query stepsCTEs
WITH RECURSIVE r AS (anchor UNION ALL ...)Series and hierarchiesCTEs
CREATE TRIGGER t AFTER UPDATE ON tblRun SQL on data changesTriggers & Procedures
OLD.col / NEW.colValues before / afterTriggers & Procedures
CALL procedure(1)Run a stored procedureTriggers & Procedures
WHERE email = ?Parameterized querySecurity
GRANT SELECT ON t TO userGive a privilegeSecurity
REVOKE INSERT ON t FROM userRemove a privilegeSecurity

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 = NULL matches no rows. Use IS NULL and IS 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