SQL cheat sheet
Clause order
Section titled “Clause order”SELECT columnsFROM tableJOIN other ON conditionWHERE row_conditionsGROUP BY columnsHAVING group_conditionsORDER BY columnsLIMIT n OFFSET m;Logical evaluation order: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT →
ORDER BY → LIMIT.
-- Inner: only matching rowsSELECT p.title, u.emailFROM posts pJOIN users u ON u.id = p.user_id;
-- Left: every post, even without a userSELECT p.title, u.emailFROM posts pLEFT JOIN users u ON u.id = p.user_id;
-- Anti-join: posts with no commentsSELECT p.*FROM posts pLEFT JOIN comments c ON c.post_id = p.idWHERE c.id IS NULL;
-- Self join: employees and managersSELECT e.name AS employee, m.name AS managerFROM employees eLEFT JOIN employees m ON m.id = e.manager_id;Aggregation
Section titled “Aggregation”SELECT user_id, COUNT(*) AS posts, MAX(created_at) AS last_postFROM postsGROUP BY user_idHAVING COUNT(*) > 5ORDER BY posts DESC;
SELECT COUNT(*) AS total, COUNT(DISTINCT user_id) AS authors, AVG(length(body)) AS avg_lengthFROM posts;WHERE filters rows before grouping; HAVING filters groups after grouping.
Window functions
Section titled “Window functions”SELECT title, user_id, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn, SUM(views) OVER (PARTITION BY user_id) AS author_viewsFROM posts;
-- Latest post per userSELECT *FROM ( SELECT p.*, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn FROM posts p) rankedWHERE rn = 1;Common table expressions
Section titled “Common table expressions”WITH recent AS ( SELECT * FROM posts WHERE created_at > now() - interval '30 days')SELECT user_id, COUNT(*) FROM recent GROUP BY user_id;Indexes
Section titled “Indexes”CREATE INDEX idx_posts_user_id ON posts (user_id);CREATE UNIQUE INDEX idx_users_email ON users (lower(email));CREATE INDEX idx_posts_user_created ON posts (user_id, created_at DESC);
-- Inspect the planEXPLAIN ANALYZE SELECT * FROM posts WHERE user_id = 42 ORDER BY created_at DESC;- Composite index order matters:
(user_id, created_at)serves filters onuser_idand onuser_id + created_at, but not oncreated_atalone. - An index on a low-selectivity column (e.g.
boolean) is often ignored. - Indexes speed reads and slow writes. Do not index everything.
LIKE '%term%'cannot use a B-tree index; use a trigram or full-text index.
Transactions
Section titled “Transactions”BEGIN;UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;COMMIT;-- or ROLLBACK;| Isolation level | Prevents | Allows |
|---|---|---|
| Read uncommitted | — | Dirty reads |
| Read committed | Dirty reads | Non-repeatable reads, phantoms |
| Repeatable read | Dirty and non-repeatable reads | Phantoms (depending on the engine) |
| Serializable | All of the above | Lowest concurrency |
-- Lock rows that you are about to updateSELECT * FROM jobs WHERE state = 'pending' FOR UPDATE SKIP LOCKED LIMIT 1;Handy patterns
Section titled “Handy patterns”-- Upsert (PostgreSQL)INSERT INTO counters (key, value) VALUES ('views', 1)ON CONFLICT (key) DO UPDATE SET value = counters.value + EXCLUDED.value;
-- PaginationSELECT * FROM posts ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET 40;
-- ExistenceSELECT EXISTS (SELECT 1 FROM users WHERE email = 'a@b.c');Interview traps
Section titled “Interview traps”COUNT(*)counts rows;COUNT(column)skipsNULL.NULL = NULLisNULL; useIS NULL.NOT IN (subquery)withNULLreturns no rows; preferNOT EXISTS.LEFT JOINplus aWHEREon the right table becomes an inner join.DISTINCTis often a sign of a missing join condition.