SQL Cheat Sheet
Queries, joins, aggregations, indexes, window functions, and performance patterns for debugging relational data in production.
Basic Queries
9 commandsSELECT * FROM usersAll rows, all columns
SELECT name, email FROM usersSpecific columns
SELECT DISTINCT city FROM usersUnique values
WHERE age > 25Filter rows
WHERE name LIKE '%ali%'Pattern match
WHERE status IN ('active','vip')Match list
WHERE email IS NULLCheck for NULL
ORDER BY created_at DESCSort descending
LIMIT 10 OFFSET 20Pagination
JOINs
6 commandsINNER JOIN orders ON u.id = o.user_idMatch both sides
LEFT JOIN orders ON ...All from left + matches
RIGHT JOIN orders ON ...All from right + matches
FULL OUTER JOIN orders ON ...All from both sides
CROSS JOIN productsCartesian product
LEFT JOIN ... WHERE o.id IS NULLUsers WITHOUT orders
Aggregations
7 commandsCOUNT(*)Count rows
COUNT(DISTINCT col)Count unique values
SUM(amount)Total
AVG(amount)Average
MAX(amount) / MIN(amount)Max / Min
GROUP BY categoryGroup rows
HAVING COUNT(*) > 5Filter groups
Window Functions
6 commandsROW_NUMBER() OVER (ORDER BY id)Sequential number
RANK() OVER (ORDER BY score DESC)Rank with gaps
DENSE_RANK() OVER (...)Rank without gaps
LAG(col, 1) OVER (ORDER BY date)Previous row value
LEAD(col, 1) OVER (ORDER BY date)Next row value
SUM(amt) OVER (PARTITION BY user_id)Running total per user
CTEs & Subqueries
4 commandsWITH cte AS (SELECT ...)Common Table Expression
WHERE id IN (SELECT ...)Subquery filter
SELECT *, (SELECT ...) AS xScalar subquery
WITH RECURSIVE cte AS (...)Recursive CTE (trees)
Data Modification
5 commandsINSERT INTO t (a,b) VALUES (1,2)Insert row
INSERT INTO t SELECT ... FROM sInsert from select
UPDATE users SET name='B' WHERE id=1Update rows
DELETE FROM users WHERE id=1Delete rows
TRUNCATE TABLE usersDelete all rows (fast)
Indexes & Performance
5 commandsCREATE INDEX idx ON t(col)Create index
CREATE UNIQUE INDEX idx ON t(col)Unique index
EXPLAIN ANALYZE SELECT ...Query execution plan
CREATE INDEX idx ON t(a, b)Composite index
DROP INDEX idxRemove index
Schema
5 commandsCREATE TABLE t (id SERIAL PRIMARY KEY, ...)Create table
ALTER TABLE t ADD COLUMN col TYPEAdd column
ALTER TABLE t DROP COLUMN colRemove column
ALTER TABLE t RENAME TO new_tRename table
DROP TABLE tDelete table
Advanced Window Functions
7 commandsNTILE(4) OVER (ORDER BY score)Split into 4 equal buckets
PERCENT_RANK() OVER (...)Percentile rank (0-1)
CUME_DIST() OVER (...)Cumulative distribution
FIRST_VALUE(col) OVER (... ROWS UNBOUNDED PRECEDING)First value in window
LAST_VALUE(col) OVER (... ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)Last value in window
SUM(amt) OVER (ORDER BY date ROWS 6 PRECEDING)Rolling 7-day sum
AVG(price) OVER (PARTITION BY category ORDER BY date ROWS 2 PRECEDING)Moving average per group
JSON Operations (PostgreSQL)
7 commandsdata->>'name'Get JSON text value
data->'address'->>'city'Nested JSON access
data @> '{"status":"active"}'JSON containment check
jsonb_array_elements(data->'items')Unnest JSON array
jsonb_set(data, '{key}', '"val"')Update JSON field
row_to_json(t)Row to JSON object
json_agg(col)Aggregate rows to JSON array
Recursive CTEs
5 commandsWITH RECURSIVE cte AS (base UNION ALL recursive)Recursive CTE pattern
-- Employee hierarchy (find all reports)Manager-employee tree
-- Category tree (parent_id self-join)Nested categories
-- Generate series (1,2,3...N)Number generation
-- Graph traversal (shortest path)BFS/DFS in SQL
Performance Tuning
8 commandsEXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...Full query plan
CREATE INDEX CONCURRENTLY idx ON t(col)Non-blocking index
CREATE INDEX idx ON t(a) WHERE status='active'Partial index
CREATE INDEX idx ON t USING GIN(col)Full-text/JSONB index
CREATE INDEX idx ON t(a) INCLUDE (b,c)Covering index
VACUUM ANALYZE tUpdate table statistics
SET enable_seqscan = offForce index scan (debug only)
SELECT pg_size_pretty(pg_total_relation_size('t'))Table size
Transactions & Locking
7 commandsBEGIN; ... COMMIT;Explicit transaction
ROLLBACK;Abort transaction
SAVEPOINT sp1; ... ROLLBACK TO sp1;Nested savepoint
SELECT ... FOR UPDATERow-level write lock
SELECT ... FOR SHARERow-level read lock
SELECT ... FOR UPDATE SKIP LOCKEDSkip locked rows (queue pattern)
SET TRANSACTION ISOLATION LEVEL SERIALIZABLEStrictest isolation
Partitioning
6 commandsCREATE TABLE t (...) PARTITION BY RANGE (date)Range partition
CREATE TABLE t_2026 PARTITION OF t FOR VALUES FROM ('2026-01-01') TO ('2027-01-01')Create partition
CREATE TABLE t (...) PARTITION BY LIST (region)List partition
CREATE TABLE t (...) PARTITION BY HASH (id)Hash partition
ALTER TABLE t DETACH PARTITION t_oldDetach old partition
SELECT * FROM pg_partitions WHERE tablename='t'List partitions