SQL cheatsheet
16 statements on two small tables, users and orders. Watch the rows that count slide into the result and the rest drop away. Written for SQLite; nearly all of it reads the same in PostgreSQL and MySQL.
SELECT name, city FROM users;Read
Group and compute
JOIN and WITH
Change data
Read
SELECT name, city FROM users;Pick some columnsSELECT * FROM users WHERE city = 'BKK';Keep only the rows where the condition holdsSELECT name FROM users ORDER BY name DESC;Sort the rows (without ORDER BY, no order is promised)SELECT name FROM users ORDER BY id LIMIT 2 OFFSET 1;Skip 1 row, take 2 (one page at a time)SELECT DISTINCT city FROM users ORDER BY city;Repeated values become one rowGroup and compute
SELECT city, COUNT(*) AS n FROM users GROUP BY city ORDER BY city;Gather rows with the same value into groups, then count eachSELECT city, COUNT(*) AS n FROM users GROUP BY city HAVING COUNT(*) > 1;Filter groups after grouping (WHERE filters rows before)SELECT user_id, SUM(total) AS spent, COUNT(*) AS n FROM orders GROUP BY user_id ORDER BY user_id;SUM, COUNT, AVG, MIN, MAX work per groupSELECT name, CASE WHEN city = 'BKK' THEN 'local' ELSE 'away' END AS zone FROM users ORDER BY id;An if / else for each rowSELECT id, user_id, total, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY total DESC) AS r FROM orders ORDER BY user_id, r;A rank within each group, rows not merged (a window function)JOIN and WITH
SELECT u.name, o.total FROM users u JOIN orders o ON o.user_id = u.id ORDER BY o.id;Pair rows of two tables; only matching pairs staySELECT u.name, o.total FROM users u LEFT JOIN orders o ON o.user_id = u.id ORDER BY u.id, o.id;Keep every row of the left table; no match on the right gives NULLWITH big AS (SELECT * FROM orders WHERE total >= 100) SELECT u.name, big.total FROM big JOIN users u ON u.id = big.user_id ORDER BY big.id;Name a sub-result (a CTE), then use it like a tableChange data
INSERT INTO users (id, name, city) VALUES (6, 'Fah', 'CNX');Add a rowUPDATE users SET city = 'CNX' WHERE id = 3;Change values in the rows that match (forget WHERE: every row)DELETE FROM users WHERE city = 'HKT';Delete the rows that match (forget WHERE: the whole table)The order SQL reads it in
You write SELECT first, but the database works in this order: FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, and LIMIT last. That's why WHERE can't use a COUNT(*) (HAVING can), and why ORDER BY can use a name you gave in SELECT.
JOIN or LEFT JOIN?
JOIN keeps only rows that have a partner. LEFT JOIN keeps every row of the left table and fills the missing side with NULL, so "users with no orders" is a LEFT JOIN plus WHERE o.id IS NULL.
Checked
"""Every statement on the SQL cheatsheet, run against SQLite on the sheet's two tables. A read prints its rows; a
change prints the users table after it (each change on a fresh copy). The page's pictures are held to these lines
(lib/cheat-sql.test.ts). Run: python3 sql.py"""
import json
import sqlite3
SEED = """
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL);
CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id), total INTEGER NOT NULL);
INSERT INTO users VALUES (1, 'Ann', 'BKK'), (2, 'Ben', 'CNX'), (3, 'Cha', 'BKK'), (4, 'Dao', 'HKT'), (5, 'Eve', 'BKK');
INSERT INTO orders VALUES (1, 1, 120), (2, 1, 80), (3, 3, 200), (4, 4, 50), (5, 4, 70);
"""
READS = {
"select": "SELECT name, city FROM users;",
"where": "SELECT * FROM users WHERE city = 'BKK';",
"order": "SELECT name FROM users ORDER BY name DESC;",
"limit": "SELECT name FROM users ORDER BY id LIMIT 2 OFFSET 1;",
"distinct": "SELECT DISTINCT city FROM users ORDER BY city;",
"group": "SELECT city, COUNT(*) AS n FROM users GROUP BY city ORDER BY city;",
"having": "SELECT city, COUNT(*) AS n FROM users GROUP BY city HAVING COUNT(*) > 1;",
"sum": "SELECT user_id, SUM(total) AS spent, COUNT(*) AS n FROM orders GROUP BY user_id ORDER BY user_id;",
"case": "SELECT name, CASE WHEN city = 'BKK' THEN 'local' ELSE 'away' END AS zone FROM users ORDER BY id;",
"window": "SELECT id, user_id, total, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY total DESC) AS r FROM orders ORDER BY user_id, r;",
"join": "SELECT u.name, o.total FROM users u JOIN orders o ON o.user_id = u.id ORDER BY o.id;",
"left": "SELECT u.name, o.total FROM users u LEFT JOIN orders o ON o.user_id = u.id ORDER BY u.id, o.id;",
"with": "WITH big AS (SELECT * FROM orders WHERE total >= 100) SELECT u.name, big.total FROM big JOIN users u ON u.id = big.user_id ORDER BY big.id;",
}
CHANGES = {
"insert": "INSERT INTO users (id, name, city) VALUES (6, 'Fah', 'CNX');",
"update": "UPDATE users SET city = 'CNX' WHERE id = 3;",
"delete": "DELETE FROM users WHERE city = 'HKT';",
}
def fresh() -> sqlite3.Connection:
db = sqlite3.connect(":memory:")
db.executescript(SEED)
return db
def show(rows: list) -> str:
return json.dumps([list(r) for r in rows], separators=(",", ":"), ensure_ascii=False)
out = []
for key, sql in READS.items():
out.append(f"{key}: {show(fresh().execute(sql).fetchall())}")
for key, sql in CHANGES.items():
db = fresh()
changed = db.execute(sql).rowcount
assert changed == 1, (key, changed) # each change touches exactly one row here
out.append(f"{key}: {show(db.execute('SELECT * FROM users ORDER BY id').fetchall())}")
assert len(out) == 16
print("\n".join(out))
python3 sql.pyIt printed:select: [["Ann","BKK"],["Ben","CNX"],["Cha","BKK"],["Dao","HKT"],["Eve","BKK"]] where: [[1,"Ann","BKK"],[3,"Cha","BKK"],[5,"Eve","BKK"]] order: [["Eve"],["Dao"],["Cha"],["Ben"],["Ann"]] limit: [["Ben"],["Cha"]] distinct: [["BKK"],["CNX"],["HKT"]] group: [["BKK",3],["CNX",1],["HKT",1]] having: [["BKK",3]] sum: [[1,200,2],[3,200,1],[4,120,2]] case: [["Ann","local"],["Ben","away"],["Cha","local"],["Dao","away"],["Eve","local"]] window: [[1,1,120,1],[2,1,80,2],[3,3,200,1],[5,4,70,1],[4,4,50,2]] join: [["Ann",120],["Ann",80],["Cha",200],["Dao",50],["Dao",70]] left: [["Ann",120],["Ann",80],["Ben",null],["Cha",200],["Dao",50],["Dao",70],["Eve",null]] with: [["Ann",120],["Cha",200]] insert: [[1,"Ann","BKK"],[2,"Ben","CNX"],[3,"Cha","BKK"],[4,"Dao","HKT"],[5,"Eve","BKK"],[6,"Fah","CNX"]] update: [[1,"Ann","BKK"],[2,"Ben","CNX"],[3,"Cha","CNX"],[4,"Dao","HKT"],[5,"Eve","BKK"]] delete: [[1,"Ann","BKK"],[2,"Ben","CNX"],[3,"Cha","BKK"],[5,"Eve","BKK"]]
Every statement on this sheet run against SQLite on the same two tables (each change on a fresh copy). The rows each line prints are the rows the pictures end on; the site's tests compare them.