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.
Why spaced repetition
Section titled “Why spaced repetition”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.
The deck
Section titled “The deck”Turn on JavaScript to study with spaced repetition. You can still browse every card below.
- Due
- 0
- Learned
- 0
- Total
- 78
Question
0 left in this round
Practice round: answers here do not change your schedule.
Keys: Space flips · 1 again · 2 got it
Progress is saved in this browser only.
Browse all cards (78)
SQL foundations How do you filter one calendar month on a timestamp column?
Read more: Filters and dates →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.SQL foundations How do you show the month of a timestamp as a column?
Read more: Filters and dates →CAST(date_trunc('month', ts) AS DATE): the first day of the month, as a date.date_truncalways returns a timestamp; from aDATEit even returnstimestamp with time zone.EXTRACT(MONTH FROM ts)gives only the number 1–12 and merges the same month of different years.SQL foundations The task says "the last 30 days". How do you write "today"?
Read more: Filters and dates →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.SQL foundations In what order does SQL process the clauses of a query, and what follows from it?
Read more: Grouping and counting →FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT
WHEREcannot see aSELECTalias; in PostgreSQLHAVINGcannot either. Repeat the expression or use a CTE.- Window functions are computed in
SELECT, so they cannot go inWHERE: filter them outside a CTE. ORDER BYruns last, so it can use an alias.
SQL foundations
COUNT(*),COUNT(col),COUNT(DISTINCT col): what does each count?Read more: Grouping and counting →COUNT(*): rows.COUNT(col): rows wherecolis notNULL.COUNT(DISTINCT col): different values.
Transactions without test purchases: 8032 rows, 180 with
refunded_at, 4 channels. After aLEFT JOIN, count a column of the right table, or every X without a match counts as 1.SQL foundations
WHEREorHAVING: which filters what?Read more: Grouping and counting →WHEREfilters rows before grouping.HAVINGfilters groups after it, by an aggregate:HAVING COUNT(*) > 300.A condition on a plain column belongs in
WHERE: fewer rows reach the grouping.SQL foundations What do
NULL = NULLandNULL <> 1return? How do you test for NULL?Read more: NULL logic →Both return
NULL, "unknown", andWHEREkeeps only rows where the condition is true.Test with
IS NULL/IS NOT NULL. For "not equal, counting NULL as a value" useIS DISTINCT FROM.SQL foundations What does
SUMreturn when there are no rows to add?Read more: NULL logic →NULL, not 0. The same forSUM(x) FILTER (WHERE …)in a group without matches, and after aLEFT JOINwithout a match.COUNTreturns 0.For money, wrap it:
COALESCE(SUM(amount_usd), 0).SQL foundations How do you get several counts per group in one pass?
Read more: Conditional aggregation →One
GROUP BYwith 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 withFILTERcan beNULL, so wrap money inCOALESCE.SQL foundations How do you compute a rate without integer division and without division by zero?
Read more: Conditional aggregation →1.0 * a / NULLIF(b, 0), ora::numeric / b.In PostgreSQL an integer divided by an integer is an integer:
7 / 2 = 3, andCOUNT(…) / COUNT(*)is usually 0.ROUNDat the very end;ROUND(x, 2)needs anumeric.SQL foundations "Every product, including products with zero sales": what are the rules?
Read more: LEFT JOIN and zeros →- Start from the table of all products:
FROM products p LEFT JOIN transactions t ON …. - Every condition on
tgoes inON. InWHEREit drops the unmatched products, and the join becomes inner. - Count a column of
t:COUNT(t.product_id);COUNT(*)gives 1 instead of 0. - Sums get
COALESCE(…, 0).
- Start from the table of all products:
SQL foundations "Merchants who never received an advance": how, and why not
NOT IN?Read more: Subqueries and CTE →FROM merchants m WHERE NOT EXISTS (SELECT 1 FROM advances v WHERE v.merchant_id = m.id), orLEFT JOIN advances v … WHERE v.advance_id IS NULL.NOT INbreaks on oneNULLin the list:1 NOT IN (2, NULL)is1 <> 2 AND 1 <> NULL, which isNULL, so no row passes.SQL foundations A
TIMESTAMPcolumn stores UTC. How do you get the day in New York?Read more: Filters and dates →Two steps:
(ts AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York')::date. Atimestamptzcolumn needs only the second step.One step on a
TIMESTAMPshifts 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.
SQL patterns Two tables each have many rows per merchant. How do you combine them?
Read more: Row multiplication →Reduce each table to one row per merchant in its own CTE, then
FROM merchants m LEFT JOINboth CTEs, withCOALESCE.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.
SQL patterns The best (or the latest) row in each group: what is the pattern?
Read more: Top N per group →- Reduce to one row per (group, item) if needed.
- In a CTE:
ROW_NUMBER() OVER (PARTITION BY group ORDER BY x DESC, id) AS rn. - Outside:
WHERE rn = 1.
The
idbreaks ties, so the result is stable. A window cannot go in theWHEREof the sameSELECT.SQL patterns Values 300, 300, 200: what do
ROW_NUMBER,RANKandDENSE_RANKgive?Read more: Top N per group →ROW_NUMBER: 1, 2, 3. Always unique, sorn = 1keeps one of the tied rows.RANK: 1, 1, 3.rank = 1keeps both.DENSE_RANK: 1, 1, 2. No gap after a tie.
"Keep ties" means
RANK.SQL patterns Share of the total and share within a group: how do you write each?
Read more: Shares and running totals →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%.SQL patterns A running total per merchant by day: the window, and the frame trap?
Read more: Shares and running totals →SUM(revenue) OVER (PARTITION BY merchant_id ORDER BY day).With
ORDER BY, the default frame isRANGE … CURRENT ROW: rows with the samedayare added together. For an exact number of rows useROWS.A moving "last 7 days" with
ROWSis right only if every day is one row: build the calendar first.SQL patterns Every day of a period, including days with zero: how?
Read more: Calendars and active periods →- A calendar:
generate_series(TIMESTAMP '2026-09-01', TIMESTAMP '2026-09-10', INTERVAL '1 day') AS g(d). LEFT JOINthe data on the day.COALESCE(…, 0).
With
TIMESTAMPliterals the series is a plaintimestamp, like the columns; with plain strings it istimestamp with time zone.- A calendar:
SQL patterns When is a subscription active at moment m?
Read more: Calendars and active periods →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 aroundORare required:ANDbinds tighter thanOR.SQL patterns Duplicate webhooks: how do you count deliveries, events and duplicates?
Read more: Duplicates and idempotency →Deliveries are
COUNT(*), events areCOUNT(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 byreceived_at), first number the copies withROW_NUMBER() OVER (PARTITION BY event_id ORDER BY received_at)and keeprn = 1.SQL patterns How do you make sure each event is stored exactly once?
Read more: Duplicates and idempotency →A
PRIMARY KEYorUNIQUEconstraint onevent_id, andINSERT … 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.
SQL patterns Sales and refunds as one stream of money per month: how?
Read more: UNION ALL and reconciliation →UNION ALLof two branches: sales with+amountbystart_time, refunds with−amountbyrefunded_at. Each branch has its own date column. Then oneGROUP BYmonth.Not
UNION: it removes equal rows, so two payments of 9.99 on the same day become one. Columns match by position.SQL patterns Reconcile two sources (expected and actual payouts): what is the shape of the query?
Read more: UNION ALL and reconciliation →- Each side reduced to one row per key in its own CTE, with its filters inside.
FULL OUTER JOINon the key, so rows missing on either side stay.COALESCE(a.key, b.key)for the key columns.- A
CASEfor the status: missing, unexpected, mismatch, ok.
SQL patterns Flow or balance: which one gets a date filter?
Read more: Money and ledgers →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.SQL patterns Retention: "customers whose first paid purchase was in July — how many bought again in August?" The two rules?
Read more: Cohorts and retention →- The cohort comes from each customer's first paid purchase over all time:
MIN(start_time)with no date window, then keep July. - "Also bought in August" is
EXISTS (…): it checks presence and does not multiply rows like aJOIN.
The rate is
1.0 * retained / cohort_size.- The cohort comes from each customer's first paid purchase over all time:
SQL traps Does
SELECT 'found' WHERE 1 NOT IN (2, NULL)return a row?Read more: NULL logic →No rows. It expands to
1 <> 2 AND 1 <> NULL, that isTRUE AND NULL, which isNULL.One
NULLin aNOT INlist or subquery, and the result is empty. For "not in the list", useNOT EXISTS.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?Read more: Conditional aggregation →ELSE 0adds a zero for every row from another channel: 1.18 instead of 13.19.For
AVG, useFILTER (WHERE channel = 'web')orCASEwithoutELSE:NULLdoes not count. For a rate,ELSE 0is right:AVG(CASE WHEN … THEN 1.0 ELSE 0 END).SQL traps The share of trials as
COUNT(…) FILTER (WHERE is_trial) / COUNT(*): what comes out?Read more: Conditional aggregation →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 (%). Write1.0 * a / bora::numeric / b, andNULLIF(b, 0)against division by zero.SQL traps Purchases on 1 September with
WHERE start_time = '2026-09-01': how many?Read more: Filters and dates →0: it matches midnight exactly.
start_time::date = '2026-09-01'gives the right 20, but an index onstart_timecannot be used. The rangestart_time >= '2026-09-01' AND start_time < '2026-09-02'gives 20 and can use the index.SQL traps Does
WHERE start_time >= '2026-09-30' - INTERVAL '30 days'run?Read more: Filters and dates →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.SQL traps
products LEFT JOIN transactions, thenWHERE t.country = 'JP', "including zeros". How many of the 20 products come out?Read more: LEFT JOIN and zeros →19:
prd_06disappears. For a product without a match,t.countryisNULL, andWHEREdrops the row. TheLEFT JOINhas become an inner join.Move every condition on the right table into
ON.SQL traps
mer_09has 2 products and 7 advances worth 1122.81. Join merchants → products → advances and sum the advances: what do you get?Read more: Row multiplication →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.
SQL traps
WHERE channel = 'web' OR channel = 'north_market' AND NOT is_test: what does it select?Read more: Filters and dates →ANDbinds tighter thanOR, so this is "web checkout, test purchases included" OR "North Market without test purchases": 5182 rows instead of 5158.When you mix
ANDandOR, use brackets:(channel = 'web' OR channel = 'north_market') AND NOT is_test.SQL traps What happens with
WHERE channel = "web"in PostgreSQL?Read more: PostgreSQL dialect →An error:
column "web" does not exist. Double quotes are for names of columns and tables; strings take single quotes:channel = 'web'.SQL traps
WHERE proceeds > 50, whereproceedsis an alias fromSELECT, orHAVING n > 1000: do they run?Read more: Grouping and counting →Both fail with
column … does not exist.WHEREruns beforeSELECT, and in PostgreSQLHAVINGdoes not seeSELECTaliases either.Repeat the expression (
HAVING COUNT(*) > 1000) or compute it in a CTE and filter outside. InORDER BYan alias works.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?Read more: Top N per group →No:
window functions are not allowed in WHERE. Windows are computed inSELECT, afterWHERE.Compute
rnin a CTE and filterWHERE rn = 1outside, or useDISTINCT ON (customer_id) … ORDER BY customer_id, start_time.SQL traps
ROUND(AVG(charged_usd)::float8, 2): does it work in PostgreSQL?Read more: PostgreSQL dialect →No:
function round(double precision, integer) does not exist.ROUNDwith a number of decimals exists only fornumeric.Cast first:
ROUND(x::numeric, 2). Some other databases accept the float version silently.SQL traps One country, one month: 39 transactions and 35 customers. Why do the numbers differ, and which one answers "how many customers"?
Read more: Grouping and counting →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.Python Group payments by customer and sum the amounts: the idiom?
Read more: dict, defaultdict and Counter →totals = defaultdict(Decimal), thentotals[p['customer']] += p['amount']in one loop, andreturn dict(totals).A new key starts at
Decimal('0'). Return a plaindict: reading a missing key of adefaultdictadds it. Money isDecimalmade from strings.Python Sort rows by amount descending, then by id ascending.
Read more: Sorting and top-k →sorted(rows, key=lambda r: (-r.amount, r.id)): a tuple key, minus for the descending number.reverse=Truewould reverse the id too. For a key you cannot negate (a string), sort twice: first by the second key, then by the first.sortedis stable, so equal items keep their order.Python Top 10 out of a million rows: do you sort everything?
Read more: Sorting and top-k →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 andO(k)memory instead ofO(n log n).In the database,
ORDER BY … LIMIT 10does the same: the plan showstop-N heapsort.Counter.most_commonbreaks ties by first appearance, not by the alphabet.Python Duplicates, or "have I seen it before?": which structure, and what does it cost?
Read more: Sets and duplicates →A
setcalledseenand one pass: membership isO(1)on average, so the whole pass isO(n).x in listchecks every element,O(n), so inside a loop it becomesO(n²). To keep the first copy of each event in order, add the id toseenwhen you keep the event.Python Events arrive out of order. How do you get the latest status per subscription?
Read more: dict, defaultdict and Counter →A
dictof "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).
Python Round a
Decimalto cents, half up and down. Why notround()?Read more: Money and Decimal →Half up:
x.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP), so0.125→0.13. Down:rounding=ROUND_DOWN, so23.9976→23.99.round(x, 2)returns aDecimal, but it uses banker's rounding (0.125→0.12) and cannot round down.Python Why not
floatfor money?Read more: Money and Decimal →Float is binary, so
0.1 + 0.2 != 0.3, and the error grows in sums.Use
Decimalcreated from strings:Decimal('0.1'). From a float only throughstr:Decimal(0.1)keeps the binary error. In the database,NUMERIC(12,2).Python Split
10.00into 3 parts that add up exactly to10.00.Read more: Money and Decimal →Work in whole cents:
q, r = divmod(1000, 3)gives(333, 1). The firstrparts 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.
Python Pay debts from a payout, oldest first, partial payments allowed: the loop?
Read more: Money and Decimal →- A negative payout raises
ValueError;left = payout. - For each debt in order:
pay = min(left, due). - Add a line only
if pay > 0, thenleft -= pay. breakwhenleft == 0. What is left goes to the merchant.
One pass over the sorted debts. A
whileloop around theforpays the first debt twice.- A negative payout raises
Python When do
[a, b)and[c, d)overlap, and how do you merge a list of periods?Read more: Intervals →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.maxkeeps a nested period from shortening it.O(n log n)because of the sort.Python Add one month to 31 January 2026 in Python.
Read more: Dates and durations →Not with
timedelta: months have different lengths. Compute the year and the month withdivmod(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.
Python A rate limiter: at most
limitrequests in anywindowseconds. The structure and the rule?Read more: Time windows →A
dequeof accepted request times. On each call:- Drop from the left while
times[0] <= now - window. - If
len(times) >= limit, returnFalse: a refused request is not recorded. - Otherwise append
nowand returnTrue.
Pass the clock in, so tests control time without sleeping.
- Drop from the left while
Python What is wrong with
def add(item, items=[])?Read more: Classes and state →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=Noneand create the list inside the function. The same trap hides in_cache={}andseen=set().Python What does
functools.wrapsdo, and where does it go?Read more: Decorators →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()andinspect.signaturefollow it, and tests can call the original through it.A decorator with a parameter has three levels: factory → decorator → wrapper.
Python The cost of a lookup in a
dict, asetand alist, and of sorting?Read more: Testing and complexity →A
dictorsetlookup isO(1)on average: they are hash tables.x in listisO(n), so inside a loop it isO(n²). Sorting isO(n log n); a heap push or pop isO(log n).Say it out loud: "It's O(n log n) because of the sort, and the memory is O(n)."
Python Parse an amount string into a
Decimalsafely: which errors do you handle?Read more: Errors and validation →Decimal('abc')raisesInvalidOperation, which is not aValueError: catch it and raiseValueError.Decimal('NaN')andDecimal('Infinity')parse without an error: reject them withis_finite().- Empty or negative input: raise
ValueErrorwith a clear message.
Then
quantizeto cents.Python How do you pass an input value into SQL from Python, and where should the work happen?
Read more: Python and SQL →Only as a parameter:
con.execute('… WHERE product_id = ?', [product_id]), or:productwith 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.
Database concepts A query is slow. How do you find out why?
Read more: Indexes and EXPLAIN →Run
EXPLAIN ANALYZEand read it from the most expensive node. Look for three things:- a
Seq Scanon 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, orBatchesabove 1.
Fix the biggest problem first, then measure again.
- a
Database concepts Does the order of columns in a composite index matter?
Read more: Indexes and EXPLAIN →Yes. An index on
(product_id, start_time)servesWHERE product_id = … AND start_time > …andWHERE product_id = …, but notWHERE start_time > …alone, at least not efficiently.Equality columns go first, the range column last.
Database concepts There is an index on
start_time. When will PostgreSQL not use it?Read more: Indexes and EXPLAIN →- When a function wraps the column:
start_time::date = …orEXTRACT(…). 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.correlationnear 1).
Check with
EXPLAIN ANALYZE. And do not index every column: each index slows down writes and takes space.- When a function wraps the column:
Database concepts Does PostgreSQL index a foreign key column automatically?
Read more: Indexes and EXPLAIN →No. Only
PRIMARY KEY,UNIQUEandEXCLUDEconstraints get an index. Joining toproducts.iduses the primary key, buttransactions.product_idhas no index until you create one.For a report on one product, an index on
(product_id, start_time)helps.Database concepts What is the N+1 problem?
Read more: Database concepts →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.Database concepts How do you make sure a webhook is processed only once?
Read more: Database concepts →A unique constraint on
event_idandINSERT … 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.
Database concepts What does a transaction give you, and what should never happen inside one?
Read more: Database concepts →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 afterCOMMITthey 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.
Database concepts Read Committed, Repeatable Read, Serializable: what does each mean in PostgreSQL?
Read more: Database concepts →- 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 Committed (the default): each query sees what was committed before that query started. Two
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?
Read more: Database concepts →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.Database concepts Two workers take the same job from a job table. How do you prevent it?
Read more: Database concepts →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.
Database concepts Can we trust the refund rate for the last month?
Read more: Database concepts →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.
Protocol and phrases The interview protocol in six steps?
Read more: Interview protocol →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".
Protocol and phrases How do you split the clock on one task?
Read more: Interview protocol →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."
Protocol and phrases What do you say in the first minute of a task?
Read more: Interview protocol →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?"
Protocol and phrases How do you ask clarifying questions without slowing down?
Read more: Interview protocol →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?"
Protocol and phrases You see the schema for the first time. Which kinds of columns turn into questions?
Read more: Interview protocol →- 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?
- A flag (
Protocol and phrases The checklist of questions before you write code?
Read more: Interview protocol →- 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.
- Today: a fixed date or
Protocol and phrases How do the agreed answers get into the code?
Read more: Interview protocol →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."
Protocol and phrases Two questions to ask yourself while you plan a SQL query?
Read more: Interview protocol →- Before a
JOIN: do both sides have many rows per key? If yes, aggregate each side in a CTE first. - Before a
GROUP BYorPARTITION 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.
- Before a
Protocol and phrases The check before "done", in order?
Read more: Interview protocol →- Walk through the comments: where is each one in the code? "Let me check the code against what we agreed."
- The number of rows: as expected?
- One row by hand, or with a separate simple query.
- Plausibility: a maximum ten times the average,
COUNT(*)againstCOUNT(DISTINCT id). - In Python, the edge cases from the comment: zero, partial, exactly on a boundary, more than enough, ties.
Protocol and phrases The interviewer asks "How do you know it works?" or "Is this what we agreed?". What do you do?
Read more: Interview protocol →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.
Protocol and phrases You are stuck. What do you say?
Read more: Think aloud →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."
How the deck works
Section titled “How the deck works”The deck uses the Leitner system: five boxes, and a card’s box sets how long it waits before it is due again.
| Box | How long a card waits there |
|---|---|
| New | Due now |
| 1 | Today, at the end of the round |
| 2 | 1 day |
| 3 | 3 days |
| 4 | 7 days |
| 5 | 16 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 (key1) 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.
Use them in Anki
Section titled “Use them in Anki”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:
- Download the file and open Anki on a computer (version 2.1.54 or later).
- Choose File → Import and select the file.
- 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.
Related topics
Section titled “Related topics”- Study plan — when to review the cards and what to practise alongside them.
- Recipes for a sheet of paper — the recipes behind many cards, one line each.
- Common mistakes — the longer story behind the trap cards.
- Interview protocol — the steps the protocol cards ask about, in full.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.