SQL cheat sheet
For beginners, students and analysts who need a quick reminder of how a query is written. It covers SELECT, WHERE, ORDER BY, GROUP BY, JOINs, subqueries, CTEs, window functions and changing data, with PostgreSQL and SQLite side by side wherever they differ. Every example was run on both databases. It's free and prints on two A4 landscape pages.
Read a table
SELECT name, species FROM pets;
Pick columns, in the order you list them.
SELECT * FROM pets;
Every column.
SELECT name, age * 12 AS age_months FROM pets;
Calculate, and name the result with AS.
SELECT DISTINCT species FROM pets;
Remove duplicate rows.
Filter rows with WHERE
SELECT name FROM pets WHERE species = 'cat' AND age > 6;
Text in 'single quotes'. Also <, <=, >=, <> (not equal).
SELECT name FROM pets WHERE (species = 'cat' OR species = 'dog') AND age > 8;
AND runs before OR: use brackets.
SELECT name FROM pets
WHERE species IN ('rabbit', 'bird');One of a list.
SELECT name FROM pets WHERE weight_kg BETWEEN 3 AND 5;
Both ends included.
SELECT name FROM pets WHERE name LIKE 'P%';
% = any text, _ = one character.
SELECT name FROM pets WHERE breed IS NULL;
Never = NULL: it matches nothing.
Sort and slice
SELECT name, age FROM pets ORDER BY age DESC, name;
DESC = highest first. Later columns break ties.
SELECT name FROM pets ORDER BY weight_kg DESC LIMIT 3 OFFSET 3;
Skip 3 rows, keep the next 3. Always sort before LIMIT.
Summarise
SELECT COUNT(*), AVG(age), MIN(age), MAX(age) FROM pets;
Aggregates collapse rows into one.
SELECT COUNT(breed), COUNT(DISTINCT species) FROM pets;
COUNT(col) skips NULLs; DISTINCT counts different values.
SELECT species, COUNT(*) AS pets FROM pets GROUP BY species ORDER BY pets DESC;
One row per group. Every plain column in SELECT goes in GROUP BY.
SELECT species, AVG(weight_kg) FROM pets GROUP BY species HAVING COUNT(*) > 3;
HAVING filters groups; WHERE filters rows before grouping.
Labels and missing values
SELECT name,
CASE WHEN age >= 8 THEN 'senior'
ELSE 'young' END AS stage
FROM pets;The first true WHEN wins; no ELSE gives NULL.
SELECT name, COALESCE(breed, 'mixed') FROM pets;
First value that isn't NULL.
SELECT NULLIF(phone, '') FROM adoption_requests;
Turns '' into NULL.
Change data
INSERT INTO pets (id, name, species, age, weight_kg, adopted, arrived_on) VALUES (99, 'Tango', 'dog', 2, 12.5, false, '2026-11-17');
Add a row. Missing columns get DEFAULT or NULL.
UPDATE pets SET age = age + 1 WHERE species = 'cat';
Without WHERE, every row changes.
DELETE FROM pets WHERE species = 'bird';
Test the WHERE as a SELECT first.
INSERT INTO pets (id, name, species, age, weight_kg, adopted, arrived_on) VALUES (3, 'Pickles', 'dog', 7, 23.0, false, '2025-09-21') ON CONFLICT (id) DO UPDATE SET weight_kg = excluded.weight_kg;
Upsert: update the row if the key exists.
Create tables
CREATE TABLE visits ( id INTEGER PRIMARY KEY, pet_id INTEGER REFERENCES pets(id), visited_on DATE NOT NULL, paid BOOLEAN DEFAULT false );
Types, keys, required columns, defaults.
CREATE INDEX pets_species ON pets (species);
Faster lookups on that column. Keep the column bare in WHERE so it's used.
CREATE VIEW waiting AS SELECT name FROM pets WHERE adopted = false;
A saved query.
The order SQL runs a query
FROM / JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT
That's why a SELECT alias can't be used in WHERE, but can be in ORDER BY.
Join tables
SELECT o.id, c.name FROM orders o JOIN customers c ON c.id = o.customer_id;
Only rows with a match. A row with 3 matches appears 3 times.
SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;
Keeps every customer; no match = NULLs.
SELECT c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;
Rows with no match (customers who never ordered).
SELECT s.name, m.name AS manager FROM staff s LEFT JOIN staff m ON m.id = s.manager_id;
Self-join: two aliases for one table.
SELECT c.name, m.name FROM customers c CROSS JOIN menu_items m;
Every combination.
Stack results
SELECT city FROM customers UNION SELECT city FROM staff;
UNION removes duplicates, UNION ALL keeps them. INTERSECT = in both, EXCEPT = in the first only.
Queries inside queries
SELECT name, price FROM menu_items
WHERE price > (SELECT AVG(price)
FROM menu_items);A subquery as one value.
SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders
WHERE status = 'cancelled');IN a list from a subquery.
WITH totals AS ( SELECT order_id, SUM(quantity) AS items FROM order_items GROUP BY order_id ) SELECT AVG(items) FROM totals;
WITH names a step; read it like a table.
WITH RECURSIVE n(x) AS ( SELECT 1 UNION ALL SELECT x + 1 FROM n WHERE x < 5 ) SELECT x FROM n;
Builds rows from its own rows until the WHERE stops it.
Classic mistakes
WHERE breed = NULL → WHERE breed IS NULL
Nothing equals NULL, not even NULL.
WHERE COUNT(*) > 3 → HAVING COUNT(*) > 3
Aggregates belong in HAVING, after GROUP BY.
COUNT(x) / COUNT(*) → 100.0 * COUNT(x) / COUNT(*)
Whole numbers divide to whole numbers.
LEFT JOIN o … WHERE o.status = 'paid' → LEFT JOIN o ON … AND o.status = 'paid'
A WHERE on the right table drops the unmatched rows again.
Window functions
SELECT category, name, price,
RANK() OVER (PARTITION BY category
ORDER BY price DESC) AS r
FROM menu_items;Ranks within each category; rows aren't collapsed. ROW_NUMBER() never ties.
SELECT name, price, SUM(price) OVER (ORDER BY price) AS running, LAG(price) OVER (ORDER BY price) AS prev FROM menu_items;
Running total, and the previous row's value.
SELECT id, weight_kg,
AVG(weight_kg) OVER (ORDER BY id
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
FROM pets;Moving average of 3 rows.
PostgreSQL vs SQLite
| PostgreSQL | SQLite | |
|---|---|---|
| Year of a date | EXTRACT(YEAR FROM d) | strftime('%Y', d) |
| Month as 2026-03 | to_char(d, 'YYYY-MM') | strftime('%Y-%m', d) |
| Add 7 days | d + 7 | date(d, '+7 days') |
| Days between | d2 - d1 | julianday(d2) - julianday(d1) |
| Join text | a || ' ' || b | a || ' ' || b |
| Text to number | CAST(x AS INTEGER) | CAST(x AS INTEGER) |
| True / false | true / false | 1 / 0 (true/false work too) |
| 7 / 2 | 3 (use 7.0 / 2) | 3 (use 7.0 / 2) |
Practise this in 5 minutes
A cheat sheet reminds you; practice makes it stick. Lesson 1 has you writing real SELECT queries on a real database in your browser, with instant feedback.
Start lesson 1Tip: in the print dialog choose Save as PDF and landscape. Want more depth? Read the SQL guides or try the free SQL tools.