Skip to content

Flashcards

Solving a drill once is not the same as recalling the recipe under time pressure. This deck turns the key ideas of the site into questions you answer from memory: the recipes, what each trap returns and how to fix it, the database concepts interviewers ask about, and the steps and phrases of the protocol. It schedules each card so that you see the hard ones often and the easy ones rarely.

You forget most of what you read within days, and each successful recall slows that forgetting down. Spaced repetition uses this: review a fact just before you would forget it, and the gap before the next review can grow. Two habits make it work. Active recall: answer from memory before seeing the answer. Spacing: return to each card at growing intervals instead of cramming them all in one evening.

Flashcards suit recipes, trap outcomes, definitions and the phrases you say: what NOT IN does with a NULL, how to round money half up, which questions to ask before you write code. They do not replace solving whole tasks out loud on a timer. Use them alongside the study plan and the interview protocol.

Turn on JavaScript to study with spaced repetition. You can still browse every card below.

Browse all cards (78)
  1. SQL foundations How do you filter one calendar month on a timestamp column?

    A half-open interval: ts >= TIMESTAMP '2026-08-01' AND ts < TIMESTAMP '2026-09-01'. The start is included, the end is not.

    Not BETWEEN '2026-08-01' AND '2026-08-31': it ends at 00:00 on 31 August and loses the rest of that day.

    Read more: Filters and dates →
  2. SQL foundations How do you show the month of a timestamp as a column?

    CAST(date_trunc('month', ts) AS DATE): the first day of the month, as a date.

    date_trunc always returns a timestamp; from a DATE it even returns timestamp with time zone. EXTRACT(MONTH FROM ts) gives only the number 1–12 and merges the same month of different years.

    Read more: Filters and dates →
  3. SQL foundations The task says "the last 30 days". How do you write "today"?

    Ask first: interview data is usually frozen. Then write a fixed, typed literal, never NOW():

    start_time >= TIMESTAMP '2026-09-30' - INTERVAL '30 days' AND start_time < TIMESTAMP '2026-09-30'

    With NOW() the window slides into days with no data, and the answer changes every day.

    Read more: Filters and dates →
  4. SQL foundations In what order does SQL process the clauses of a query, and what follows from it?

    FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT

    • WHERE cannot see a SELECT alias; in PostgreSQL HAVING cannot either. Repeat the expression or use a CTE.
    • Window functions are computed in SELECT, so they cannot go in WHERE: filter them outside a CTE.
    • ORDER BY runs last, so it can use an alias.
    Read more: Grouping and counting →
  5. SQL foundations COUNT(*), COUNT(col), COUNT(DISTINCT col): what does each count?
    • COUNT(*): rows.
    • COUNT(col): rows where col is not NULL.
    • COUNT(DISTINCT col): different values.

    Transactions without test purchases: 8032 rows, 180 with refunded_at, 4 channels. After a LEFT JOIN, count a column of the right table, or every X without a match counts as 1.

    Read more: Grouping and counting →
  6. SQL foundations WHERE or HAVING: which filters what?

    WHERE filters rows before grouping. HAVING filters groups after it, by an aggregate: HAVING COUNT(*) > 300.

    A condition on a plain column belongs in WHERE: fewer rows reach the grouping.

    Read more: Grouping and counting →
  7. SQL foundations What do NULL = NULL and NULL <> 1 return? How do you test for NULL?

    Both return NULL, "unknown", and WHERE keeps only rows where the condition is true.

    Test with IS NULL / IS NOT NULL. For "not equal, counting NULL as a value" use IS DISTINCT FROM.

    Read more: NULL logic →
  8. SQL foundations What does SUM return when there are no rows to add?

    NULL, not 0. The same for SUM(x) FILTER (WHERE …) in a group without matches, and after a LEFT JOIN without a match. COUNT returns 0.

    For money, wrap it: COALESCE(SUM(amount_usd), 0).

    Read more: NULL logic →
  9. SQL foundations How do you get several counts per group in one pass?

    One GROUP BY with a conditional aggregate per counter: COUNT(*) FILTER (WHERE is_trial) AS trials.

    The portable form is SUM(CASE WHEN … THEN 1 ELSE 0 END). A sum with FILTER can be NULL, so wrap money in COALESCE.

    Read more: Conditional aggregation →
  10. SQL foundations How do you compute a rate without integer division and without division by zero?

    1.0 * a / NULLIF(b, 0), or a::numeric / b.

    In PostgreSQL an integer divided by an integer is an integer: 7 / 2 = 3, and COUNT(…) / COUNT(*) is usually 0. ROUND at the very end; ROUND(x, 2) needs a numeric.

    Read more: Conditional aggregation →
  11. SQL foundations "Every product, including products with zero sales": what are the rules?
    1. Start from the table of all products: FROM products p LEFT JOIN transactions t ON ….
    2. Every condition on t goes in ON. In WHERE it drops the unmatched products, and the join becomes inner.
    3. Count a column of t: COUNT(t.product_id); COUNT(*) gives 1 instead of 0.
    4. Sums get COALESCE(…, 0).
    Read more: LEFT JOIN and zeros →
  12. SQL foundations "Merchants who never received an advance": how, and why not NOT IN?

    FROM merchants m WHERE NOT EXISTS (SELECT 1 FROM advances v WHERE v.merchant_id = m.id), or LEFT JOIN advances v … WHERE v.advance_id IS NULL.

    NOT IN breaks on one NULL in the list: 1 NOT IN (2, NULL) is 1 <> 2 AND 1 <> NULL, which is NULL, so no row passes.

    Read more: Subqueries and CTE →
  13. SQL foundations A TIMESTAMP column stores UTC. How do you get the day in New York?

    Two steps: (ts AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York')::date. A timestamptz column needs only the second step.

    One step on a TIMESTAMP shifts the wrong way: 02:00 UTC on 1 September becomes 06:00, not 22:00 on 31 August.

    Ask which time zone defines "a day" for the people who read the report.

    Read more: Filters and dates →
  14. SQL patterns Two tables each have many rows per merchant. How do you combine them?

    Reduce each table to one row per merchant in its own CTE, then FROM merchants m LEFT JOIN both CTEs, with COALESCE.

    Joining the raw rows pairs every row of one table with every row of the other, and every sum is multiplied. Check one merchant with a separate simple query.

    Read more: Row multiplication →
  15. SQL patterns The best (or the latest) row in each group: what is the pattern?
    1. Reduce to one row per (group, item) if needed.
    2. In a CTE: ROW_NUMBER() OVER (PARTITION BY group ORDER BY x DESC, id) AS rn.
    3. Outside: WHERE rn = 1.

    The id breaks ties, so the result is stable. A window cannot go in the WHERE of the same SELECT.

    Read more: Top N per group →
  16. SQL patterns Values 300, 300, 200: what do ROW_NUMBER, RANK and DENSE_RANK give?
    • ROW_NUMBER: 1, 2, 3. Always unique, so rn = 1 keeps one of the tied rows.
    • RANK: 1, 1, 3. rank = 1 keeps both.
    • DENSE_RANK: 1, 1, 2. No gap after a tie.

    "Keep ties" means RANK.

    Read more: Top N per group →
  17. SQL patterns Share of the total and share within a group: how do you write each?

    Of the total: 100.0 * x / SUM(x) OVER (). Within a group: 100.0 * x / SUM(x) OVER (PARTITION BY merchant_id).

    A window sees the rows left after GROUP BY. If you partition by the key that already has one row per group, every row gets 100%.

    Read more: Shares and running totals →
  18. SQL patterns A running total per merchant by day: the window, and the frame trap?

    SUM(revenue) OVER (PARTITION BY merchant_id ORDER BY day).

    With ORDER BY, the default frame is RANGE … CURRENT ROW: rows with the same day are added together. For an exact number of rows use ROWS.

    A moving "last 7 days" with ROWS is right only if every day is one row: build the calendar first.

    Read more: Shares and running totals →
  19. SQL patterns Every day of a period, including days with zero: how?
    1. A calendar: generate_series(TIMESTAMP '2026-09-01', TIMESTAMP '2026-09-10', INTERVAL '1 day') AS g(d).
    2. LEFT JOIN the data on the day.
    3. COALESCE(…, 0).

    With TIMESTAMP literals the series is a plain timestamp, like the columns; with plain strings it is timestamp with time zone.

    Read more: Calendars and active periods →
  20. SQL patterns When is a subscription active at moment m?

    start_time <= m AND end_time > m AND (refunded_at IS NULL OR refunded_at > m)

    The period is half-open, [start_time, end_time), and a refund ends the subscription. The brackets around OR are required: AND binds tighter than OR.

    Read more: Calendars and active periods →
  21. SQL patterns Duplicate webhooks: how do you count deliveries, events and duplicates?

    Deliveries are COUNT(*), events are COUNT(DISTINCT event_id), duplicates are the difference.

    COUNT(DISTINCT) removes repeats only inside its own group. If a copy can fall into another group (another day by received_at), first number the copies with ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY received_at) and keep rn = 1.

    Read more: Duplicates and idempotency →
  22. SQL patterns How do you make sure each event is stored exactly once?

    A PRIMARY KEY or UNIQUE constraint on event_id, and INSERT … ON CONFLICT (event_id) DO NOTHING.

    To add to a stored value instead: ON CONFLICT (key) DO UPDATE SET v = t.v + EXCLUDED.v.

    The database enforces it even when two workers insert at the same time.

    Read more: Duplicates and idempotency →
  23. SQL patterns Sales and refunds as one stream of money per month: how?

    UNION ALL of two branches: sales with +amount by start_time, refunds with −amount by refunded_at. Each branch has its own date column. Then one GROUP BY month.

    Not UNION: it removes equal rows, so two payments of 9.99 on the same day become one. Columns match by position.

    Read more: UNION ALL and reconciliation →
  24. SQL patterns Reconcile two sources (expected and actual payouts): what is the shape of the query?
    1. Each side reduced to one row per key in its own CTE, with its filters inside.
    2. FULL OUTER JOIN on the key, so rows missing on either side stay.
    3. COALESCE(a.key, b.key) for the key columns.
    4. A CASE for the status: missing, unexpected, mismatch, ok.
    Read more: UNION ALL and reconciliation →
  25. SQL patterns Flow or balance: which one gets a date filter?

    A flow is a sum over a period (revenue in the last 30 days): it has a date window.

    A balance is a state at a moment (what a merchant owes today): a sum over all time up to that moment. The ledger only adds signed entries (advance +, fee +, repayment −), so the debt is SUM(amount_usd) of every entry before today.

    With a 30-day window on the ledger, mer_03 "owes" −45.96; over all time it owes 116.39.

    Read more: Money and ledgers →
  26. SQL patterns Retention: "customers whose first paid purchase was in July — how many bought again in August?" The two rules?
    1. The cohort comes from each customer's first paid purchase over all time: MIN(start_time) with no date window, then keep July.
    2. "Also bought in August" is EXISTS (…): it checks presence and does not multiply rows like a JOIN.

    The rate is 1.0 * retained / cohort_size.

    Read more: Cohorts and retention →
  27. SQL traps Does SELECT 'found' WHERE 1 NOT IN (2, NULL) return a row?

    No rows. It expands to 1 <> 2 AND 1 <> NULL, that is TRUE AND NULL, which is NULL.

    One NULL in a NOT IN list or subquery, and the result is empty. For "not in the list", use NOT EXISTS.

    Read more: NULL logic →
  28. SQL traps The average price of paid web checkout purchases (no trials) as AVG(CASE WHEN channel = 'web' THEN charged_usd ELSE 0 END): what goes wrong?

    ELSE 0 adds a zero for every row from another channel: 1.18 instead of 13.19.

    For AVG, use FILTER (WHERE channel = 'web') or CASE without ELSE: NULL does not count. For a rate, ELSE 0 is right: AVG(CASE WHEN … THEN 1.0 ELSE 0 END).

    Read more: Conditional aggregation →
  29. SQL traps The share of trials as COUNT(…) FILTER (WHERE is_trial) / COUNT(*): what comes out?

    The result is 0. Both counts are integers, and an integer divided by an integer is an integer.

    With 100.0 * … in front, the same expression gives 11.3 (%). Write 1.0 * a / b or a::numeric / b, and NULLIF(b, 0) against division by zero.

    Read more: Conditional aggregation →
  30. SQL traps Purchases on 1 September with WHERE start_time = '2026-09-01': how many?

    0: it matches midnight exactly.

    start_time::date = '2026-09-01' gives the right 20, but an index on start_time cannot be used. The range start_time >= '2026-09-01' AND start_time < '2026-09-02' gives 20 and can use the index.

    Read more: Filters and dates →
  31. SQL traps Does WHERE start_time >= '2026-09-30' - INTERVAL '30 days' run?

    No: invalid input syntax for type interval: "2026-09-30". A quoted string has no type at first and takes the type of its neighbour, here an interval.

    Fix: TIMESTAMP '2026-09-30' - INTERVAL '30 days', which is 2026-08-31 00:00. The last 30 days then have 483 transactions. Habit: always type the date literal.

    Read more: Filters and dates →
  32. SQL traps products LEFT JOIN transactions, then WHERE t.country = 'JP', "including zeros". How many of the 20 products come out?

    19: prd_06 disappears. For a product without a match, t.country is NULL, and WHERE drops the row. The LEFT JOIN has become an inner join.

    Move every condition on the right table into ON.

    Read more: LEFT JOIN and zeros →
  33. SQL traps mer_09 has 2 products and 7 advances worth 1122.81. Join merchants → products → advances and sum the advances: what do you get?

    14 rows and 2245.62, exactly double. Products and advances are not related to each other, so every product is paired with every advance: 2 × 7.

    Reduce each table to one row per merchant first, then join.

    Read more: Row multiplication →
  34. SQL traps WHERE channel = 'web' OR channel = 'north_market' AND NOT is_test: what does it select?

    AND binds tighter than OR, so this is "web checkout, test purchases included" OR "North Market without test purchases": 5182 rows instead of 5158.

    When you mix AND and OR, use brackets: (channel = 'web' OR channel = 'north_market') AND NOT is_test.

    Read more: Filters and dates →
  35. SQL traps What happens with WHERE channel = "web" in PostgreSQL?

    An error: column "web" does not exist. Double quotes are for names of columns and tables; strings take single quotes: channel = 'web'.

    Read more: PostgreSQL dialect →
  36. SQL traps WHERE proceeds > 50, where proceeds is an alias from SELECT, or HAVING n > 1000: do they run?

    Both fail with column … does not exist. WHERE runs before SELECT, and in PostgreSQL HAVING does not see SELECT aliases either.

    Repeat the expression (HAVING COUNT(*) > 1000) or compute it in a CTE and filter outside. In ORDER BY an alias works.

    Read more: Grouping and counting →
  37. SQL traps The first transaction of each customer with WHERE ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY start_time) = 1: does it run?

    No: window functions are not allowed in WHERE. Windows are computed in SELECT, after WHERE.

    Compute rn in a CTE and filter WHERE rn = 1 outside, or use DISTINCT ON (customer_id) … ORDER BY customer_id, start_time.

    Read more: Top N per group →
  38. SQL traps ROUND(AVG(charged_usd)::float8, 2): does it work in PostgreSQL?

    No: function round(double precision, integer) does not exist. ROUND with a number of decimals exists only for numeric.

    Cast first: ROUND(x::numeric, 2). Some other databases accept the float version silently.

    Read more: PostgreSQL dialect →
  39. SQL traps One country, one month: 39 transactions and 35 customers. Why do the numbers differ, and which one answers "how many customers"?

    Some customers had several transactions that month. "How many customers" is COUNT(DISTINCT customer_id).

    Ask first what counts as one customer: a customer_id, or a pair of customer and product.

    Read more: Grouping and counting →
  40. Python Group payments by customer and sum the amounts: the idiom?

    totals = defaultdict(Decimal), then totals[p['customer']] += p['amount'] in one loop, and return dict(totals).

    A new key starts at Decimal('0'). Return a plain dict: reading a missing key of a defaultdict adds it. Money is Decimal made from strings.

    Read more: dict, defaultdict and Counter →
  41. Python Sort rows by amount descending, then by id ascending.

    sorted(rows, key=lambda r: (-r.amount, r.id)): a tuple key, minus for the descending number.

    reverse=True would reverse the id too. For a key you cannot negate (a string), sort twice: first by the second key, then by the first. sorted is stable, so equal items keep their order.

    Read more: Sorting and top-k →
  42. Python Top 10 out of a million rows: do you sort everything?

    No. heapq.nsmallest(10, rows, key=lambda r: (-r.revenue, r.customer_id)) keeps a heap of the 10 best so far: O(n log k) time and O(k) memory instead of O(n log n).

    In the database, ORDER BY … LIMIT 10 does the same: the plan shows top-N heapsort. Counter.most_common breaks ties by first appearance, not by the alphabet.

    Read more: Sorting and top-k →
  43. Python Duplicates, or "have I seen it before?": which structure, and what does it cost?

    A set called seen and one pass: membership is O(1) on average, so the whole pass is O(n).

    x in list checks every element, O(n), so inside a loop it becomes O(n²). To keep the first copy of each event in order, add the id to seen when you keep the event.

    Read more: Sets and duplicates →
  44. Python Events arrive out of order. How do you get the latest status per subscription?

    A dict of "best so far": for each event, replace the stored one only if the new timestamp is later. One pass, O(n).

    Compare timestamps, not the order of arrival, and agree on a rule for equal timestamps (for example, the later one in the list wins).

    Read more: dict, defaultdict and Counter →
  45. Python Round a Decimal to cents, half up and down. Why not round()?

    Half up: x.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP), so 0.125 → 0.13. Down: rounding=ROUND_DOWN, so 23.9976 → 23.99.

    round(x, 2) returns a Decimal, but it uses banker's rounding (0.125 → 0.12) and cannot round down.

    Read more: Money and Decimal →
  46. Python Why not float for money?

    Float is binary, so 0.1 + 0.2 != 0.3, and the error grows in sums.

    Use Decimal created from strings: Decimal('0.1'). From a float only through str: Decimal(0.1) keeps the binary error. In the database, NUMERIC(12,2).

    Read more: Money and Decimal →
  47. Python Split 10.00 into 3 parts that add up exactly to 10.00.

    Work in whole cents: q, r = divmod(1000, 3) gives (333, 1). The first r parts get one extra cent: 3.34, 3.33, 3.33.

    Dividing and rounding each part separately gives parts that do not add up to the amount.

    Read more: Money and Decimal →
  48. Python Pay debts from a payout, oldest first, partial payments allowed: the loop?
    1. A negative payout raises ValueError; left = payout.
    2. For each debt in order: pay = min(left, due).
    3. Add a line only if pay > 0, then left -= pay.
    4. break when left == 0. What is left goes to the merchant.

    One pass over the sorted debts. A while loop around the for pays the first debt twice.

    Read more: Money and Decimal →
  49. Python When do [a, b) and [c, d) overlap, and how do you merge a list of periods?

    Overlap: a < d and c < b. Touching ends (b == c) do not overlap.

    Merge: sort by start, then one pass. If a period starts before (or, if touching counts, at) the end of the last merged one, extend that one to max(end); otherwise start a new one. max keeps a nested period from shortening it. O(n log n) because of the sort.

    Read more: Intervals →
  50. Python Add one month to 31 January 2026 in Python.

    Not with timedelta: months have different lengths. Compute the year and the month with divmod(month - 1 + n, 12), then cap the day: min(day, calendar.monthrange(year, month)[1]). The result is 28 February 2026.

    For renewals, count each from the original date: chaining gives 28 March instead of 31 March.

    Read more: Dates and durations →
  51. Python A rate limiter: at most limit requests in any window seconds. The structure and the rule?

    A deque of accepted request times. On each call:

    1. Drop from the left while times[0] <= now - window.
    2. If len(times) >= limit, return False: a refused request is not recorded.
    3. Otherwise append now and return True.

    Pass the clock in, so tests control time without sleeping.

    Read more: Time windows →
  52. Python What is wrong with def add(item, items=[])?

    The default list is created once, when the function is defined, and it is shared between calls: the second call sees the items of the first.

    Use items=None and create the list inside the function. The same trap hides in _cache={} and seen=set().

    Read more: Classes and state →
  53. Python What does functools.wraps do, and where does it go?

    On the inner wrapper, because the wrapper replaces the original function. It copies the name, the docstring and the module, so logs and tools still see the real name. It also sets __wrapped__ to the original: help() and inspect.signature follow it, and tests can call the original through it.

    A decorator with a parameter has three levels: factory → decorator → wrapper.

    Read more: Decorators →
  54. Python The cost of a lookup in a dict, a set and a list, and of sorting?

    A dict or set lookup is O(1) on average: they are hash tables. x in list is O(n), so inside a loop it is O(n²). Sorting is O(n log n); a heap push or pop is O(log n).

    Say it out loud: "It's O(n log n) because of the sort, and the memory is O(n)."

    Read more: Testing and complexity →
  55. Python Parse an amount string into a Decimal safely: which errors do you handle?
    • Decimal('abc') raises InvalidOperation, which is not a ValueError: catch it and raise ValueError.
    • Decimal('NaN') and Decimal('Infinity') parse without an error: reject them with is_finite().
    • Empty or negative input: raise ValueError with a clear message.

    Then quantize to cents.

    Read more: Errors and validation →
  56. Python How do you pass an input value into SQL from Python, and where should the work happen?

    Only as a parameter: con.execute('… WHERE product_id = ?', [product_id]), or :product with SQLAlchemy. Never an f-string: that is SQL injection, and parameters also handle types and quotes.

    Filter and aggregate in SQL, close to the data and its indexes; bring a small result into Python. Keep in Python only what is hard in SQL, like an allocation loop.

    Read more: Python and SQL →
  57. Database concepts A query is slow. How do you find out why?

    Run EXPLAIN ANALYZE and read it from the most expensive node. Look for three things:

    • a Seq Scan on a big table where you expected an index;
    • estimated rows very different from actual rows: often stale statistics, so run ANALYZE, or columns that depend on each other (CREATE STATISTICS);
    • a sort or hash that spills to disk: external merge Disk, or Batches above 1.

    Fix the biggest problem first, then measure again.

    Read more: Indexes and EXPLAIN →
  58. Database concepts Does the order of columns in a composite index matter?

    Yes. An index on (product_id, start_time) serves WHERE product_id = … AND start_time > … and WHERE product_id = …, but not WHERE start_time > … alone, at least not efficiently.

    Equality columns go first, the range column last.

    Read more: Indexes and EXPLAIN →
  59. Database concepts There is an index on start_time. When will PostgreSQL not use it?
    • When a function wraps the column: start_time::date = … or EXTRACT(…). Compare the raw column with a range, or create an expression index.
    • When the query takes a large share of the table: a sequential scan is cheaper then. How large depends on the physical order: rows written in time order keep a date range cheap for longer (pg_stats.correlation near 1).

    Check with EXPLAIN ANALYZE. And do not index every column: each index slows down writes and takes space.

    Read more: Indexes and EXPLAIN →
  60. Database concepts Does PostgreSQL index a foreign key column automatically?

    No. Only PRIMARY KEY, UNIQUE and EXCLUDE constraints get an index. Joining to products.id uses the primary key, but transactions.product_id has no index until you create one.

    For a report on one product, an index on (product_id, start_time) helps.

    Read more: Indexes and EXPLAIN →
  61. Database concepts What is the N+1 problem?

    One query for a list, then one more query for each item: 100 invoices become 101 queries.

    The fix is a join, or one query with WHERE id IN (…) for all the items.

    Read more: Database concepts →
  62. Database concepts How do you make sure a webhook is processed only once?

    A unique constraint on event_id and INSERT … ON CONFLICT (event_id) DO NOTHING. The database guarantees it even with two workers.

    A check in application code ("select, then insert if missing") is not enough: two workers can both pass the check at the same time.

    The insert and the processing commit in one transaction: if the worker crashes after the insert, both roll back, and the retry processes the event.

    Read more: Database concepts →
  63. Database concepts What does a transaction give you, and what should never happen inside one?

    All or nothing: either every change is saved, or none. For example, a payout and its ledger entries are written together. Other sessions do not see the changes before COMMIT, and after COMMIT they survive a crash.

    Never call an external service (a bank, a marketplace API) inside a transaction. It holds locks and a connection while it waits, and if it rolls back after a timeout, the external request may already be sent.

    Read more: Database concepts →
  64. Database concepts Read Committed, Repeatable Read, Serializable: what does each mean in PostgreSQL?
    • Read Committed (the default): each query sees what was committed before that query started. Two SELECTs in one transaction can differ.
    • Repeatable Read: one snapshot for the whole transaction. Updating a row that another transaction changed raises an error; retry.
    • Serializable: the result is as if transactions ran one after another; otherwise one fails with a serialization error, and the application retries it.
    Read more: Database concepts →
  65. Database concepts A limit of 1000, a debt of 700. Two workers each check the limit and issue an advance of 250 at the same time. What happens, and how do you prevent it?

    Both read 700, both see 950 ≤ 1000, both insert: the debt becomes 1200. Repeatable Read does not help, because they insert different rows.

    Lock the merchant row first: SELECT … FROM merchants WHERE id = … FOR UPDATE. The second worker waits for the first to commit, then sees 950 and refuses. Or use Serializable and retry on the error.

    Read more: Database concepts →
  66. Database concepts Two workers take the same job from a job table. How do you prevent it?

    SELECT … FOR UPDATE SKIP LOCKED: each worker locks different rows and skips the ones already taken.

    Add a unique key on the business key too, so a duplicate fails even if something else goes wrong.

    Read more: Database concepts →
  67. Database concepts Can we trust the refund rate for the last month?

    Not fully. Refunds come after the purchase: in the practice data, a median of about 11 days and 21 days at most. Any month younger than that looks better than it really is.

    Mark those months as incomplete, or compare months by the refund rate within the first 30 days, counting only purchases that already had 30 days.

    Read more: Database concepts →
  68. Protocol and phrases The interview protocol in six steps?

    REPEAT → ASK (in one batch) → COMMENTS → PLAN → CODE → CHECK against the comments.

    The main idea: keep the requirements in comments, not in your head, and check the code against them before you say "done".

    Read more: Interview protocol →
  69. Protocol and phrases How do you split the clock on one task?

    Easy / medium / hard:

    • Restate the task and one row of the result: 1 / 1 / 1–2 min.
    • The environment once, then 3–5 task questions in one batch, answers as comments: 1–2 / about 3 / up to 5 min.
    • A plan of 2–4 steps, out loud: 1 / 1–2 / 2 min.
    • So code starts at about minute 4 / 6 / 9, and gets the target time.
    • The rest: index, complexity, production.

    The clock: 25 min, or the target plus 10 when the target is over 15. Out of time for questions? "Let me start with these assumptions and adjust later."

    Read more: Interview protocol →
  70. Protocol and phrases What do you say in the first minute of a task?

    Restate the task in your own words and name one row of the result: "So the result has one row per merchant, with columns merchant_id and revenue. Is that right?"

    If you cannot name one row, the task is not understood yet. Ask: "Can you show me what one row of the result should look like?"

    Read more: Interview protocol →
  71. Protocol and phrases How do you ask clarifying questions without slowing down?

    In one batch, each with the answer you would assume: "A few questions, with what I'd assume. Today is 2026-09-30, not now(). Test purchases excluded. Refunds: excluded or net? Which channels? Ties by id. Is that right?"

    One more question covers data quality: "Anything I should know about duplicates, test data, missing values?"

    Read more: Interview protocol →
  72. Protocol and phrases You see the schema for the first time. Which kinds of columns turn into questions?
    • A flag (is_test, is_trial): include or exclude?
    • A category (channel, type): group by it to see the values. Which of these count?
    • A time that can be NULL (refunded_at): what does NULL mean here?
    • Two similar amounts (revenue_usd, charged_usd): which one is right?
    • Several dates: which one puts a row into the period?
    • An event or payment id: can the same one arrive twice?
    Read more: Interview protocol →
  73. Protocol and phrases The checklist of questions before you write code?
    • Today: a fixed date or now()?
    • Every narrowing word (enrolled, paid, active, last 30 days): which column?
    • Filters: test purchases, trials, promo access, refunds, which channels.
    • The result row: one row per what? Include zeros and empty groups?
    • Ties and order.
    • Edge cases: negative, zero, empty.
    • Who uses the result: finance or a product dashboard decides refunds and rounding.

    Go through it in your head; ask three to five of these, the ones that change the result most, and write the rest as assumptions in the comments.

    Read more: Interview protocol →
  74. Protocol and phrases How do the agreed answers get into the code?

    As a block of comments at the top, written while you listen. The first line is RESULT (one row per …), then today, the filters and the definitions, and the last line is PLAN (2–3 steps).

    In Python: RETURNS, the rules, the edge cases, PLAN. Say: "Let me write your answers down as comments, so we both see them."

    Read more: Interview protocol →
  75. Protocol and phrases Two questions to ask yourself while you plan a SQL query?
    1. Before a JOIN: do both sides have many rows per key? If yes, aggregate each side in a CTE first.
    2. Before a GROUP BY or PARTITION BY: within what am I choosing or counting? If the key is the same as the grouping of the previous step, the step does nothing.

    In Python, say the rule in one sentence before the code.

    Read more: Interview protocol →
  76. Protocol and phrases The check before "done", in order?
    1. Walk through the comments: where is each one in the code? "Let me check the code against what we agreed."
    2. The number of rows: as expected?
    3. One row by hand, or with a separate simple query.
    4. Plausibility: a maximum ten times the average, COUNT(*) against COUNT(DISTINCT id).
    5. In Python, the edge cases from the comment: zero, partial, exactly on a boundary, more than enough, ties.
    Read more: Interview protocol →
  77. Protocol and phrases The interviewer asks "How do you know it works?" or "Is this what we agreed?". What do you do?

    Run it, do not explain it: "Good point, let me run it." Then two checks: exactly on the boundary, and one second before it.

    To "Is this what we agreed?", do not say "yes" at once: "Let me re-read what we agreed", then check the comments against the code.

    Read more: Interview protocol →
  78. Protocol and phrases You are stuck. What do you say?

    Never stay silent for more than 30 seconds; say what you are thinking about.

    • "I'm not sure how to … . Can I think out loud?"
    • "Let me go back to the example and check it again."
    • "Could you point me in the right direction?"
    • With five minutes left: "I'll finish the main case first, then the edge cases."
    Read more: Think aloud →

The deck uses the Leitner system: five boxes, and a card’s box sets how long it waits before it is due again.

BoxHow long a card waits there
NewDue now
1Today, at the end of the round
21 day
33 days
47 days
516 days, and it stays in box 5
  • Got it (key 2) moves the card up one box, where it waits that box’s interval; a new card goes straight to box 2. Again (key 1) sends it back to box 1, and it returns at the end of the current round.
  • Due counts cards to review now in the selected section; Learned counts cards in box 2 or higher.
  • By default the weakest cards come first. Shuffle mixes the order instead.
  • When nothing is due, you can run a practice round over every card in the section. Practice rounds do not change the schedule.
  • Progress is saved in your browser and shared by the English and Russian versions: a card you know in one language counts in the other. Clearing site data or using a private window starts from scratch. Reset progress puts every card back to new.
  • Without JavaScript, open Browse all cards to read every question and answer.

Anki is a free spaced-repetition program for computers and phones. Both decks have the same cards as the deck above; each answer ends with a link to the page on this site.

To import a deck:

  1. Download the file and open Anki on a computer (version 2.1.54 or later).
  2. Choose File → Import and select the file.
  3. Anki reads the settings from the file header: tab-separated, HTML allowed, note type Basic, deck Live Coding Map. Check them in the dialog and click Import.

Each card is tagged live-coding plus a section tag such as lcm::traps, so you can study one section with a filtered deck. Cards carry stable IDs: when the site publishes a new version of the deck, importing it again updates the existing notes and keeps your review history.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.