Skip to content

SQL cheat sheet

SELECT columns
FROM table
JOIN other ON condition
WHERE row_conditions
GROUP BY columns
HAVING group_conditions
ORDER BY columns
LIMIT n OFFSET m;

Logical evaluation order: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.

-- Inner: only matching rows
SELECT p.title, u.email
FROM posts p
JOIN users u ON u.id = p.user_id;
-- Left: every post, even without a user
SELECT p.title, u.email
FROM posts p
LEFT JOIN users u ON u.id = p.user_id;
-- Anti-join: posts with no comments
SELECT p.*
FROM posts p
LEFT JOIN comments c ON c.post_id = p.id
WHERE c.id IS NULL;
-- Self join: employees and managers
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
SELECT user_id, COUNT(*) AS posts, MAX(created_at) AS last_post
FROM posts
GROUP BY user_id
HAVING COUNT(*) > 5
ORDER BY posts DESC;
SELECT COUNT(*) AS total,
COUNT(DISTINCT user_id) AS authors,
AVG(length(body)) AS avg_length
FROM posts;

WHERE filters rows before grouping; HAVING filters groups after grouping.

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_views
FROM posts;
-- Latest post per user
SELECT *
FROM (
SELECT p.*, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn
FROM posts p
) ranked
WHERE rn = 1;
WITH recent AS (
SELECT * FROM posts WHERE created_at > now() - interval '30 days'
)
SELECT user_id, COUNT(*) FROM recent GROUP BY user_id;
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 plan
EXPLAIN ANALYZE SELECT * FROM posts WHERE user_id = 42 ORDER BY created_at DESC;
  • Composite index order matters: (user_id, created_at) serves filters on user_id and on user_id + created_at, but not on created_at alone.
  • 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.
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 update
SELECT * FROM jobs WHERE state = 'pending' FOR UPDATE SKIP LOCKED LIMIT 1;
-- Upsert (PostgreSQL)
INSERT INTO counters (key, value) VALUES ('views', 1)
ON CONFLICT (key) DO UPDATE SET value = counters.value + EXCLUDED.value;
-- Pagination
SELECT * FROM posts ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET 40;
-- Existence
SELECT EXISTS (SELECT 1 FROM users WHERE email = 'a@b.c');
  • COUNT(*) counts rows; COUNT(column) skips NULL.
  • NULL = NULL is NULL; use IS NULL.
  • NOT IN (subquery) with NULL returns no rows; prefer NOT EXISTS.
  • LEFT JOIN plus a WHERE on the right table becomes an inner join.
  • DISTINCT is often a sign of a missing join condition.