Recipes for a sheet of paper
Each line is a recipe: what to write, the trap next to it, and a link to the topic page that explains it. Copy the list by hand onto one sheet of paper, SQL on the front and Python on the back. Copying it is the revision.
- ★ One month —
ts >= TIMESTAMP '2026-08-01' AND ts < TIMESTAMP '2026-09-01'. NotBETWEEN: it loses the last day after 00:00. A month as a column isCAST(date_trunc('month', ts) AS DATE);EXTRACT(MONTH FROM ts)merges the years. → Filters and dates - ★ Every X, even with zero —
FROM x LEFT JOIN y ON …, every condition onyinsideON,COUNT(y.col),COALESCE(…, 0). A condition onyinWHEREremoves the zeros;COUNT(*)gives 1 instead of 0. → LEFT JOIN and zeros - ★ Two tables to one key — reduce each table to one row per key in its own CTE (or the rows multiply). Then
FROMthe table that defines the rows,LEFT JOINthe other one,COALESCE. A plainJOINdrops unmatched rows on both sides. → Row multiplication - ★ Best or latest per group — reduce to (group, item), then
ROW_NUMBER() OVER (PARTITION BY group ORDER BY x DESC, id), andrn = 1in the outer query. A window cannot go in theWHEREof the sameSELECT.DESCapplies to one column. To keep ties, useRANK(). → Top N per group - ★ Share — of the total:
x / SUM(x) OVER (); within a group:OVER (PARTITION BY group). Partitioning by a key that has one row per group gives every row 100%. → Shares and running totals - ★ Several counters —
COUNT(*) FILTER (WHERE …), several in oneGROUP BY. A rate is1.0 * a / NULLIF(b, 0): an integer divided by an integer is an integer. → CASE, FILTER and rates - ★ Never happened —
NOT EXISTS (…)orLEFT JOIN … WHERE y.id IS NULL. NotNOT IN: oneNULLin the list, and the result is empty. → CTE and EXISTS - ★ Duplicates — deliveries are
COUNT(*), events areCOUNT(DISTINCT id). If a copy can land in another group, firstROW_NUMBER() OVER (PARTITION BY id …)and keeprn = 1. The cure isUNIQUEplusON CONFLICT DO NOTHING. → Duplicates and idempotency - Flow or balance — a flow (revenue for a month) has a date filter. A balance (what a merchant owes, an account balance) is a
SUMover all time up to “today”. → Money and ledgers - Active at moment m —
start_time <= m AND end_time > m AND (refunded_at IS NULL OR refunded_at > m). The brackets aroundORare required. → Calendars and active periods - Two feeds (sales and refunds) —
UNION ALL, each branch with its own date, then oneGROUP BY. NotUNION: it merges equal amounts. → UNION ALL and reconciliation - Reconcile two sources — each side to one row per key, then
FULL OUTER JOIN,COALESCEof the keys and aCASEfor the status. Filters go inside the CTEs. → UNION ALL and reconciliation - At least one row (a cohort) —
EXISTS (SELECT 1 …)with a condition that links it to the outer row. AJOINwould multiply the rows. A cohort is defined by theMINover all time. → Cohorts and retention - Every day, even empty —
generate_series, thenLEFT JOIN, thenCOALESCE. → Calendars and active periods - Once in the database —
PRIMARY KEYorUNIQUEplusINSERT … ON CONFLICT DO NOTHING. An upsert isON CONFLICT (key) DO UPDATE SET v = t.v + EXCLUDED.v. → Duplicates and idempotency
Python
Section titled “Python”- ★ Group and sum —
defaultdict(Decimal), and returndict(d). Money is aDecimalmade from a string. → dict and Counter - ★ Sort by several keys —
key=lambda r: (-r.amount, r.id).reverse=Truewould reverse theidtoo. → Sorting and top-k - ★ Top k —
heapq.nsmallest(k, rows, key=…):O(n log k). On equal counts,Counter.most_commonkeeps the order of first appearance, not the alphabet. → Sorting and top-k - ★ Seen before, duplicates — a
setand one pass.x in listinside a loop isO(n²). → Sets and duplicates - ★ Latest record per key — a
dictof “best so far”. Compare the timestamps, not the order of arrival. → dict and Counter - ★ Allocate a payout —
pay = min(left, due),if pay > 0, stop whenleft == 0. A negative input raisesValueError. → Money and Decimal - ★ Round money —
quantize(Decimal("0.01"), rounding=ROUND_HALF_UP).round()on aDecimalis banker’s rounding: 0.125 → 0.12. → Money and Decimal - ★ Overlap of
[a, b)and[c, d)—a < d and c < b. To merge periods: sort by start, then one pass. → Intervals - Split an amount into parts — work in whole cents:
divmod(cents, n), then one extra cent to each of the first parts. → Money and Decimal - Time window (a rate limiter) — a
deque; drop from the left whiletimes[0] <= now - window. Do not record refused requests. → Time windows - Add months — year and month with
//and%, the day ismin(day, monthrange(y, m)[1]). Count each renewal from the original date, not from the previous one. → Dates and durations - Reconcile two dicts —
a.keys() - b.keys(),a.keys() & b.keys(), thensorted. → Sets and duplicates - Decorator —
@functools.wraps(func)on thewrapper; keep state in an attribute such aswrapper.calls. A decorator with a parameter needs one more level. → Decorators - Input and time —
Decimal("abc")raisesInvalidOperation: turn it intoValueError, and rejectNaNwithis_finite(). Pass the clock in as aclockparameter. Aware and naive datetimes cannot be compared. → Errors and validation, Classes and state
How to use the sheet
Section titled “How to use the sheet”- Copy, do not print. By hand you read every symbol, and small details such as the brackets in SQL recipe 10 stay with you.
- Recall before you read. Cover the right part of a line, say the trap out loud, then check.
- Run the ★ lines. Turn each ★ recipe into a full query or function in an empty editor and run it on the practice dataset.
- Read it on the morning of the interview, together with common mistakes.
Related topics
Section titled “Related topics”- SQL cheat sheet — the same recipes with syntax, the order of execution and the traps to check before “done”.
- Python cheat sheet — the standard-library tools behind the Python recipes.
- Common mistakes — what goes wrong when a recipe is forgotten under time pressure.
- Flashcards — the recipes as questions to answer from memory.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.