Money and reconciliation
Money tasks compare two sources and expect every cent to add up: webhooks that arrive twice, payouts from the partner marketplaces against what the sales say, advances that break the rules, and what each merchant still owes. The last task builds the daily table that such reports read. The habits: one row per real event before you count, UNION ALL and FULL OUTER JOIN for two sources, a status computed before you filter on it, a balance as the sum of signed entries, and a load that replaces rows instead of adding to them. They build on UNION ALL and reconciliation, Money and ledgers and Duplicates and idempotency; the advances program is described on the dataset page.
Q11. Duplicate webhooks
Section titled “Q11. Duplicate webhooks”Webhooks can arrive more than once with the same event_id. For September 2026, count unique events per day and type, and how many duplicate deliveries we received.
Output columns: day (DATE), type, events, duplicatesOrder: ORDER BY day, type
Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Which copy is the real one?
The first by received_at. The others are duplicates.
Is a duplicate an exact copy of the event?
Yes: same event_id, type and occurred_at; only received_at differs.
Which day?
The day of occurred_at (UTC), from 2026-09-01 to 2026-09-29.
Days or types with no events?
Leave them out.
About the data: webhook_events
- The same event can arrive several times with the same event_id (at-least-once delivery).
- occurred_at is when the event happened, received_at is when it reached us. The first copy is the earliest by received_at.
A few rows
SELECT event_id, type, occurred_at, received_atFROM webhook_eventsWHERE event_id = 'evt_000834'ORDER BY received_at;| event_id | type | occurred_at | received_at |
|---|---|---|---|
| evt_000834 | renewal | 2026-09-06 22:50:13 | 2026-09-06 22:50:40 |
| evt_000834 | renewal | 2026-09-06 22:50:13 | 2026-09-06 23:00:29 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Hint: what the interviewer would nudge
Before you count anything, mark which copy of each event_id arrived first by received_at. Then events and duplicates come out of the same GROUP BY.
Say it: The real fix is a unique constraint on event_id with ON CONFLICT DO NOTHING at ingest.
Reference solution
WITH ranked AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY received_at) AS rn FROM webhook_events)SELECT CAST(occurred_at AS DATE) AS day, type, COUNT(*) FILTER (WHERE rn = 1) AS events, COUNT(*) FILTER (WHERE rn > 1) AS duplicatesFROM rankedWHERE occurred_at >= TIMESTAMP '2026-09-01' AND occurred_at < TIMESTAMP '2026-09-30'GROUP BY 1, 2ORDER BY day, type;Expected output
| day | type | events | duplicates |
|---|---|---|---|
| 2026-09-01 | expiration | 7 | 0 |
| 2026-09-01 | purchase | 3 | 1 |
| 2026-09-01 | refund | 1 | 0 |
| 2026-09-01 | renewal | 17 | 0 |
| 2026-09-02 | expiration | 3 | 0 |
| 2026-09-02 | purchase | 6 | 0 |
| 2026-09-02 | refund | 1 | 0 |
| 2026-09-02 | renewal | 4 | 0 |
| 2026-09-03 | expiration | 5 | 0 |
| 2026-09-03 | purchase | 6 | 0 |
| 2026-09-03 | renewal | 14 | 1 |
| 2026-09-04 | expiration | 3 | 0 |
| 2026-09-04 | purchase | 4 | 1 |
| 2026-09-04 | renewal | 6 | 1 |
| 2026-09-05 | expiration | 5 | 0 |
| 2026-09-05 | purchase | 7 | 0 |
| 2026-09-05 | renewal | 18 | 1 |
| 2026-09-06 | expiration | 2 | 0 |
| 2026-09-06 | purchase | 5 | 1 |
| 2026-09-06 | renewal | 10 | 2 |
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. The channels deliver webhooks at least once, so one event can arrive twice. We need to know how many real events there were and how many extra deliveries.
Steps.
- Number the copies of each event before grouping:
ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY received_at).rn = 1is the event,rn > 1is a duplicate. GROUP BYthe day ofoccurred_atand the type, withCOUNT(*) FILTER (WHERE rn = 1)andCOUNT(*) FILTER (WHERE rn > 1).
Traps.
- The day is the day of
occurred_at, when the event happened, not ofreceived_at. In the practice data every copy of a September event arrives on the day the event happened, so grouping byreceived_atlooks right. The hidden edge-case data that Check also uses has copies that arrive after midnight, and that version fails there. - Count the extra copies, not the events that had copies: an event delivered three times has two duplicates. No practice event arrived more than twice; the hidden data has one that did.
- The range is 1–29 September, as the task says:
occurred_at < '2026-09-30'.
A shorter way. Here a duplicate is an exact copy, with the same type and occurred_at, so all copies fall into the same group. Then COUNT(DISTINCT event_id) and COUNT(*) - COUNT(DISTINCT event_id) give the same 87 rows. But DISTINCT finds repeats only inside one group. If copies could differ, for example when you group by received_at, it would count one event in two groups. If you take this route, name the assumption.
Check. 87 rows; in total 580 events and 25 duplicates. In the whole table there are 1285 deliveries of 1226 events, and no event arrived more than twice.
Follow-up. “How do we stop duplicates?” At ingest: UNIQUE (event_id) and INSERT … ON CONFLICT (event_id) DO NOTHING.
In production. That is the real fix. With a unique index on event_id, a duplicate never gets into the table, and this query is no longer needed.
Q12. Reconcile channel payouts with expected proceeds
Section titled “Q12. Reconcile channel payouts with expected proceeds”The partner marketplaces pay merchants once a month. Compare what each channel should have paid (from our transactions) with what it really paid (channel_payouts), for January–August 2026, and list every problem. Expected proceeds of a (merchant, channel, month): only north_market and south_market. Each sale adds charged_usd * (1 - fee_rate) in the month of start_time; each refund subtracts the same amount in the month of refunded_at. Round the sum to 2 decimals. Paid: the sum of the payout rows of that (merchant, channel, period_month). Status, the first rule that applies: 'duplicate_payout' (more than one payout row); 'unexpected_payout' (paid, nothing expected); 'not_due_yet' (no payout, and today, 2026-09-30, is before the due date: the first day of the next month + 32 days for north_market, + 14 days for south_market); 'missing_payout' (no payout, and it is due); 'matched' (|expected - paid| <= 1.00, FX rounding); otherwise 'mismatch'. Show every row that is not 'matched'.
Output columns: merchant_id, channel, period_month (DATE), expected_usd, paid_usd, statusOrder: ORDER BY merchant_id, channel, period_month
Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Test purchases?
Excluded.
Expected proceeds of 0 or less, when refunds are bigger than sales?
Ignore those: nothing is expected for that month.
Only one side exists. What goes in expected_usd or paid_usd?
NULL, not 0: it shows which side is missing.
Two payout rows and nothing expected?
'duplicate_payout': the first rule that applies wins.
About the data: transactions, products, channel_payouts
- channel_payouts is what the channels actually paid: one row per payout to a merchant for a channel and a period_month (the first day of the sales month).
- What they should have paid is calculated from transactions (through products to merchant_id).
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Hint: what the interviewer would nudge
Build the two sides separately: expected proceeds per merchant, channel and month, and the payouts grouped the same way. Then think about which join keeps a row that exists on only one side.
Say it: A unique key on (merchant_id, channel, period_month) would stop a duplicate payout at write time.
Reference solution
WITH movements AS ( -- sales count in the month of the purchase SELECT pr.merchant_id, t.channel, CAST(date_trunc('month', t.start_time) AS DATE) AS period_month, t.charged_usd * (1 - t.fee_rate) AS net FROM transactions t JOIN products pr ON pr.id = t.product_id WHERE NOT t.is_test AND t.channel IN ('north_market', 'south_market') UNION ALL -- refunds are taken back in the month of the refund SELECT pr.merchant_id, t.channel, CAST(date_trunc('month', t.refunded_at) AS DATE), -t.charged_usd * (1 - t.fee_rate) FROM transactions t JOIN products pr ON pr.id = t.product_id WHERE NOT t.is_test AND t.channel IN ('north_market', 'south_market') AND t.refunded_at IS NOT NULL),expected AS ( SELECT merchant_id, channel, period_month, ROUND(SUM(net), 2) AS expected_usd FROM movements WHERE period_month BETWEEN DATE '2026-01-01' AND DATE '2026-08-01' GROUP BY 1, 2, 3 HAVING ROUND(SUM(net), 2) > 0),paid AS ( SELECT merchant_id, channel, period_month, SUM(amount_usd) AS paid_usd, COUNT(*) AS payouts FROM channel_payouts GROUP BY 1, 2, 3),joined AS ( SELECT COALESCE(e.merchant_id, p.merchant_id) AS merchant_id, COALESCE(e.channel, p.channel) AS channel, COALESCE(e.period_month, p.period_month) AS period_month, e.expected_usd, p.paid_usd, p.payouts FROM expected e FULL OUTER JOIN paid p ON p.merchant_id = e.merchant_id AND p.channel = e.channel AND p.period_month = e.period_month)SELECT *FROM ( SELECT merchant_id, channel, period_month, expected_usd, paid_usd, CASE WHEN payouts > 1 THEN 'duplicate_payout' WHEN expected_usd IS NULL THEN 'unexpected_payout' WHEN paid_usd IS NULL AND TIMESTAMP '2026-09-30' < period_month + INTERVAL '1 month' + CASE WHEN channel = 'north_market' THEN INTERVAL '32 days' ELSE INTERVAL '14 days' END THEN 'not_due_yet' WHEN paid_usd IS NULL THEN 'missing_payout' WHEN ABS(expected_usd - paid_usd) <= 1.00 THEN 'matched' ELSE 'mismatch' END AS status FROM joined) AS sWHERE status <> 'matched' -- not "NOT (payouts = 1 AND ...)": NULL would drop the missing rowsORDER BY merchant_id, channel, period_month;Expected output
| merchant_id | channel | period_month | expected_usd | paid_usd | status |
|---|---|---|---|---|---|
| mer_01 | north_market | 2026-01-01 | 57.76 | 64.69 | mismatch |
| mer_01 | north_market | 2026-04-01 | 17.82 | 15.15 | mismatch |
| mer_01 | north_market | 2026-08-01 | 137.62 | NULL | not_due_yet |
| mer_01 | south_market | 2026-08-01 | 41.59 | NULL | missing_payout |
| mer_02 | north_market | 2026-02-01 | 328.10 | NULL | missing_payout |
| mer_02 | north_market | 2026-05-01 | 369.39 | NULL | missing_payout |
| mer_02 | north_market | 2026-06-01 | 363.75 | 727.50 | duplicate_payout |
| mer_02 | north_market | 2026-08-01 | 347.64 | NULL | not_due_yet |
| mer_02 | south_market | 2026-07-01 | 272.10 | NULL | missing_payout |
| mer_03 | north_market | 2026-03-01 | 25.45 | 21.63 | mismatch |
| mer_03 | north_market | 2026-08-01 | 161.43 | NULL | not_due_yet |
| mer_04 | north_market | 2026-04-01 | 66.15 | 56.23 | mismatch |
| mer_04 | north_market | 2026-08-01 | 238.60 | NULL | not_due_yet |
| mer_05 | north_market | 2026-05-01 | 132.91 | 142.21 | mismatch |
| mer_05 | north_market | 2026-08-01 | 118.90 | NULL | not_due_yet |
| mer_06 | north_market | 2026-04-01 | 102.77 | 92.49 | mismatch |
| mer_06 | north_market | 2026-08-01 | 463.92 | NULL | not_due_yet |
| mer_06 | south_market | 2026-01-01 | 210.66 | NULL | missing_payout |
| mer_07 | north_market | 2026-06-01 | 120.57 | 135.04 | mismatch |
| mer_07 | north_market | 2026-08-01 | 146.06 | NULL | not_due_yet |
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. Compare what a partner marketplace should have paid with what arrived. The advances program depends on it: an advance is paid against a marketplace payout that has not arrived yet.
Steps.
movements: sales and refunds with a minus sign in one feed (UNION ALL). A sale counts in the month ofstart_time, a refund in the month ofrefunded_at.expectedper (merchant, channel, month), rounded, above 0 only.paidfromchannel_payouts: the sum and the number of rows.FULL OUTER JOINon all three keys, withCOALESCEfor the key columns.- A
CASEwith the statuses in priority order. Keep every row that is not ‘matched’.
Traps.
- You need a
FULL JOIN: either side can be missing. ALEFT JOINfromexpectedloses a payout that nobody expected. The practice data has none, but the hidden edge-case data that Check also uses has one, and theCASEmust label it ‘unexpected_payout’. - ‘not_due_yet’: the payout does not have to be there yet. The August North Market payout is due on 3 October (1 September + 32 days), so on 30 September it is not missing. The August South Market payout was due on 15 September.
- Ignore expected proceeds of 0 or less:
HAVING ROUND(SUM(net), 2) > 0. In the hidden edge-case data one month has a refund and no sales, so its expected proceeds are negative. Without theHAVINGthat month gets a ‘mismatch’ against −27.99 instead of ‘unexpected_payout’. - When one side is missing, its column stays NULL, as the task says.
COALESCE(paid_usd, 0)looks tidy, but 0 reads as “a payout of zero”, not “no payout”, and Check fails. - With NULLs, compute the status first, then filter on it.
WHERE NOT (payouts = 1 AND ABS(expected_usd - paid_usd) <= 1.00)looks the same, but for a missing payout the condition is NULL, and those rows disappear: 12 rows instead of 32.
Check. 32 rows: 12 ‘not_due_yet’, 11 ‘mismatch’, 8 ‘missing_payout’ and 1 ‘duplicate_payout’ (mer_02, north_market, June: 363.75 expected, 727.50 paid in two rows).
In production. A unique key on channel_payouts (merchant_id, channel, period_month) would stop the duplicate payout when it is written. For the expected amounts, an index on transactions(start_time).
Q13. Check merchant advances
Section titled “Q13. Check merchant advances”We advanced money to merchants against their future channel payouts. Find advances that break our rules: (1) 'over_limit': amount_usd > ROUND(0.70 * expected proceeds of the advance's merchant, channel and period_month, 2) + 0.01. Expected proceeds of a (merchant, channel, month): north_market and south_market only, test purchases excluded. Each sale adds charged_usd * (1 - fee_rate) in the month of start_time; each refund subtracts the same amount in the month of refunded_at. Round the sum to 2 decimals. No date filter. (2) 'before_enrollment': the merchant is not enrolled (advances_enrolled_at IS NULL), or created_at < advances_enrolled_at. (3) 'duplicate': another advance with the same idempotency_key was created earlier.
Output columns: advance_id, merchant_id, issueOrder: ORDER BY advance_id, issue
Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
One row per advance?
One row per broken rule.
No expected proceeds for that month?
Treat them as 0.
Why + 0.01 in the limit?
Advances are computed by another system with its own rounding, so 7 of the 38 are exactly one cent above ROUND(0.70 * expected, 2). One cent is rounding, not a broken rule.
Two advances with the same key and the same created_at?
That does not happen here. If it did, the one with the smaller advance_id would be the original.
About the data: advances, merchants, transactions, products
- advances are early payouts to merchants: merchant_id, channel, period_month, amount_usd, idempotency_key = 'merchant:channel:month'.
- merchants.advances_enrolled_at is when the merchant joined the advances program; NULL means not enrolled.
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Hint: what the interviewer would nudge
Start with one row per advance and one boolean column per rule. When the flags look right, turn them into one output row per broken rule.
Say it: A unique index on idempotency_key prevents the duplicate advance instead of finding it later.
Reference solution
WITH movements AS ( SELECT p.merchant_id, t.channel, CAST(date_trunc('month', t.start_time) AS DATE) AS period_month, t.charged_usd * (1 - t.fee_rate) AS net FROM transactions t JOIN products p ON p.id = t.product_id WHERE NOT t.is_test AND t.channel IN ('north_market', 'south_market') UNION ALL SELECT p.merchant_id, t.channel, CAST(date_trunc('month', t.refunded_at) AS DATE), -t.charged_usd * (1 - t.fee_rate) FROM transactions t JOIN products p ON p.id = t.product_id WHERE NOT t.is_test AND t.channel IN ('north_market', 'south_market') AND t.refunded_at IS NOT NULL),expected AS ( SELECT merchant_id, channel, period_month, ROUND(SUM(net), 2) AS expected_usd FROM movements GROUP BY 1, 2, 3),checked AS ( SELECT adv.advance_id, adv.merchant_id, adv.amount_usd > ROUND(0.70 * COALESCE(e.expected_usd, 0), 2) + 0.01 AS over_limit, m.advances_enrolled_at IS NULL OR adv.created_at < m.advances_enrolled_at AS before_enrollment, ROW_NUMBER() OVER (PARTITION BY adv.idempotency_key ORDER BY adv.created_at, adv.advance_id) > 1 AS duplicate FROM advances adv JOIN merchants m ON m.id = adv.merchant_id LEFT JOIN expected e ON e.merchant_id = adv.merchant_id AND e.channel = adv.channel AND e.period_month = adv.period_month)SELECT advance_id, merchant_id, 'over_limit' AS issue FROM checked WHERE over_limitUNION ALLSELECT advance_id, merchant_id, 'before_enrollment' FROM checked WHERE before_enrollmentUNION ALLSELECT advance_id, merchant_id, 'duplicate' FROM checked WHERE duplicateORDER BY advance_id, issue;Expected output
| advance_id | merchant_id | issue |
|---|---|---|
| adv_0007 | mer_03 | before_enrollment |
| adv_0024 | mer_07 | over_limit |
| adv_0028 | mer_09 | duplicate |
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. Risk control: advances above the limit, advances made before the merchant joined the program, and duplicates by idempotency_key.
Steps.
expectedas in Q12, without the date filter.checked: one row per advance with three boolean flags.UNION ALLover the flags: one output row per broken rule.
Traps.
- An advance can have no expected proceeds. Use a
LEFT JOINandCOALESCE(e.expected_usd, 0). An inner join drops the advance with all its flags, and withoutCOALESCEthe limit is NULL, soover_limitis never true. - Subtract refunds in the month of the refund, as in Q12. In the hidden edge-case data one advance is over the limit only because a refund in that month lowers the expected proceeds; without the refunds it looks fine, and Check fails.
- Keep the one-cent tolerance from the task:
amount_usd > ROUND(0.70 * expected, 2) + 0.01. Rounding can move an amount one cent above the limit: adv_0003 is 96.34 against a limit of 96.33. Without the+ 0.01, the query returns 10 rows instead of 3; withamount_usd > 0.70 * expectedand noROUND, 22. - “Not enrolled” is
advances_enrolled_at IS NULL. A comparison with NULL is never true, so it needs its own branch. Every practice advance belongs to an enrolled merchant. The hidden edge-case data has one that does not, so Check fails without theIS NULLbranch. - A duplicate is
ROW_NUMBER() OVER (PARTITION BY idempotency_key ORDER BY created_at, advance_id) > 1. The second key follows the task’s tie rule; no two copies here share acreated_at.GROUP BY idempotency_key HAVING COUNT(*) > 1would flag both copies, and the first one is legitimate.
Check. Three rows:
- adv_0007 (mer_03), ‘before_enrollment’: made on 2 June, and the merchant enrolled on 19 June.
- adv_0024 (mer_07), ‘over_limit’: 38.13, while the limit is 70% of 45.87, that is 32.11.
- adv_0028 (mer_09), ‘duplicate’: the same key as adv_0027, created 41 seconds later, most likely a retry.
In production. A unique index on idempotency_key: the duplicate advance is never written. This is more reliable than any check after the fact.
Q14. Outstanding balance per merchant
Section titled “Q14. Outstanding balance per merchant”Using the ledger, show how much each merchant still owes us, how many advances are still open and when the oldest open advance was made.
Output columns: merchant_id, outstanding_usd, open_advances, oldest_open_advance_on (DATE)Order: ORDER BY outstanding_usd DESC, merchant_id
Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Ledger signs?
advance and fee entries are positive; repayment entries are negative. The balance is the sum.
Open advance?
An advance_id whose entries sum to more than 0.
As of when?
Entries with created_at < 2026-09-30.
Which merchants?
Only those who owe more than 0.
Can an advance be overpaid, so its balance is negative?
No. A repayment never exceeds what is owed, so every advance balance is 0 or more.
"When the advance was made" — which date?
created_at of the 'advance' entry (the same as advances.created_at). The fee entry is written at the same moment, repayments come later.
About the data: ledger_entries
- Each advance has several ledger rows with the same advance_id: advance and fee are positive, repayment is negative.
- What a merchant owes is the sum of their amount_usd. An advance is open while the sum of its rows is above 0.
A few rows
SELECT entry_id, merchant_id, advance_id, entry_type, amount_usd, created_atFROM ledger_entriesWHERE advance_id = 'adv_0001'ORDER BY created_at, entry_id;| entry_id | merchant_id | advance_id | entry_type | amount_usd | created_at |
|---|---|---|---|---|---|
| le_00001 | mer_01 | adv_0001 | advance | 68.38 | 2026-07-02 10:00:00 |
| le_00002 | mer_01 | adv_0001 | fee | 2.05 | 2026-07-02 10:00:00 |
| le_00003 | mer_01 | adv_0001 | repayment | -70.43 | 2026-08-02 09:00:00 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Hint: what the interviewer would nudge
Sum the ledger per advance first, so you know which advances are still open. Then roll those rows up per merchant.
Say it: Index on (merchant_id, created_at); in production I would also keep the balance updated in the same transaction.
Reference solution
WITH per_advance AS ( SELECT merchant_id, advance_id, SUM(amount_usd) AS outstanding_usd, MIN(created_at) FILTER (WHERE entry_type = 'advance') AS advanced_at FROM ledger_entries WHERE created_at < TIMESTAMP '2026-09-30' GROUP BY 1, 2)SELECT merchant_id, SUM(outstanding_usd) AS outstanding_usd, COUNT(*) FILTER (WHERE outstanding_usd > 0) AS open_advances, CAST(MIN(advanced_at) FILTER (WHERE outstanding_usd > 0) AS DATE) AS oldest_open_advance_onFROM per_advanceGROUP BY merchant_idHAVING SUM(outstanding_usd) > 0ORDER BY outstanding_usd DESC, merchant_id;Expected output
| merchant_id | outstanding_usd | open_advances | oldest_open_advance_on |
|---|---|---|---|
| mer_11 | 619.68 | 3 | 2026-08-02 |
| mer_09 | 241.30 | 2 | 2026-08-02 |
| mer_04 | 172.03 | 1 | 2026-09-02 |
| mer_01 | 129.21 | 2 | 2026-09-02 |
| mer_03 | 116.39 | 1 | 2026-09-02 |
| mer_07 | 105.31 | 1 | 2026-09-02 |
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. A ledger is a journal of money movements: the advance and the fee are positive, repayments are negative. The balance is not stored anywhere; it is the sum of the entries. This is the usual design for money.
Steps.
- A CTE
per_advance:GROUP BY merchant_id, advance_id→ the sum of the entries and the date of theadvanceentry. - Per merchant:
SUM,COUNT(*) FILTER (WHERE outstanding_usd > 0),MIN(advanced_at) FILTER (WHERE outstanding_usd > 0), andHAVING SUM(outstanding_usd) > 0.
Traps.
- Whether an advance is open is decided by the sum of all its entries, not by one entry.
- “The oldest open advance” is a
MINover open advances only. Without the filter, mer_11 gets 2026-07-02, an advance that is already repaid; the right answer is 2026-08-02. - The date of an advance is the
created_atof itsadvanceentry:MIN(created_at) FILTER (WHERE entry_type = 'advance'). The task promises that the fee has the same time and repayments come later, so a plainMINgives the same date. The filter does not depend on that promise. - Only entries before 30 September 00:00 count:
created_at < '2026-09-30'. The hidden edge-case data has a repayment exactly at that moment, so a query without the filter, or with<=, fails there.
Check. 6 merchants. The first is mer_11: 619.68, 3 open advances, the oldest from 2026-08-02.
Follow-up. “How do you issue a new advance safely?” Check the debt and write the new entries in one transaction, with the merchant’s row locked by SELECT … FOR UPDATE. Otherwise two workers can both pass the limit check at the same time (see Database concepts).
In production. An index on ledger_entries (merchant_id, created_at). Many systems also keep the balance in its own column and update it in the same transaction as the ledger entry.
Q15. Daily revenue table per merchant and channel
Section titled “Q15. Daily revenue table per merchant and channel”Reports should read a small daily table, not every transaction. Build that table, fill it and use it, in one script of five steps. (1) CREATE TABLE daily_merchant_revenue: day (DATE), merchant_id, channel, sales (INTEGER), gross_usd, refunds_usd, net_usd (NUMERIC(12,2)), with a primary key that allows one row per merchant, channel and day. (2) Load the days [2026-09-01, 2026-09-30) so that running the load twice is safe: INSERT … SELECT … ON CONFLICT … DO UPDATE, or DELETE those days and INSERT them again in one transaction. A sale is a paid transaction (SCHEMA.md): not a trial, not a test purchase, not promo. It counts on the day of its start_time. sales and gross_usd: the number of sales and their SUM(charged_usd). refunds_usd: SUM(charged_usd) of the refunded sales. net_usd: what the merchant keeps: each sale adds charged_usd * (1 - fee_rate), each refund takes the same amount back, rounded to 2 decimals. (3) Run the same load again, as a retried job would. Nothing may change. (4) A refund arrived late: keep the given UPDATE as it is, then load only its day, [2026-09-22, 2026-09-23). (5) The report, read from daily_merchant_revenue only: September so far, per merchant and channel, with the number of days that have at least one sale and the sums of the four measures.
Output columns: merchant_id, channel, days_with_sales, sales, gross_usd, refunds_usd, net_usdOrder: ORDER BY merchant_id, channel
Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Which time zone defines the day?
UTC: every timestamp in the data is UTC.
Which day does a refund count on: the day of the sale or the day of the refund?
The day of refunded_at, as in the proceeds of a month (SCHEMA.md). So a day that is already loaded does not change when one of its sales is refunded later.
A merchant and channel with no sale and no refund on a day: a row of zeros, or no row?
No row: a missing row means 0. A day with refunds and no sales does get a row, with sales = 0.
A refund arrives after its day was loaded. What happens to that row?
The job loads that day again, and the load replaces the row with the new totals. Step (4) does exactly that.
About the data: transactions, products
- A transaction reaches its merchant through products: transactions.product_id → products.id → products.merchant_id.
- A refund is not a row of its own: it is the same transaction with refunded_at set. Its sale and its refund can fall on different days, even in different months.
- fee_rate is the channel's fee: 0.15 or 0.30 on a marketplace, 0.03 on the web checkout. charged_usd * (1 - fee_rate) is what the merchant keeps of one sale.
- In the example, t_005659 was sold on 31 August and refunded on 17 September; t_007681 is the sale that step (4) refunds late.
- Every run starts from the same data and is rolled back at the end, so CREATE TABLE and UPDATE are safe to run again and again.
A few rows
SELECT t.transaction_id AS id, p.merchant_id, t.channel, t.start_time, t.refunded_at, t.charged_usd, t.fee_rateFROM transactions tJOIN products p ON p.id = t.product_idWHERE t.transaction_id IN ('t_005659', 't_007681')ORDER BY t.start_time;| id | merchant_id | channel | start_time | refunded_at | charged_usd | fee_rate |
|---|---|---|---|---|---|---|
| t_005659 | mer_01 | north_market | 2026-08-31 07:09:58 | 2026-09-17 06:25:44 | 39.99 | 0.1500 |
| t_007681 | mer_06 | north_market | 2026-09-15 04:56:52 | NULL | 79.99 | 0.1500 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- Every run starts from the same data, so one script does all five steps. -- (1) CREATE TABLE daily_merchant_revenue -- (2) The load for [2026-09-01, 2026-09-30) -- (3) The same load again -- (4) A late refund: keep this UPDATE as it is. UPDATE transactions SET refunded_at = TIMESTAMP '2026-09-22 10:20:00', revenue_usd = 0 WHERE transaction_id = 't_007681'; -- Then the load for [2026-09-22, 2026-09-23) only. -- (5) The report
Hint: what the interviewer would nudge
A refund counts on its own day, and that day may have no sales at all. So put sales and refunds into one list of rows, each with its own day, before you group. Then ask what the second run should do with a row that is already in the table.
Say it: The primary key is the grain, and the load replaces a day's rows instead of adding to them, so a retry or a late refund only means loading that day again.
Reference solution
-- 1. The grain is one row per UTC day, merchant and channel: the primary key enforces it.CREATE TABLE daily_merchant_revenue ( day DATE NOT NULL, merchant_id TEXT NOT NULL, channel TEXT NOT NULL, sales INTEGER NOT NULL, gross_usd NUMERIC(12,2) NOT NULL, refunds_usd NUMERIC(12,2) NOT NULL, net_usd NUMERIC(12,2) NOT NULL, PRIMARY KEY (day, merchant_id, channel));
-- 2. The load for [2026-09-01, 2026-09-30). A sale counts on the day of start_time, a refund on-- the day of refunded_at, so a day with refunds and no sales gets a row too. ON CONFLICT-- replaces the totals (EXCLUDED), never adds to them: a second run changes nothing.INSERT INTO daily_merchant_revenue (day, merchant_id, channel, sales, gross_usd, refunds_usd, net_usd)SELECT day, merchant_id, channel, SUM(sales), SUM(gross), SUM(refunded), ROUND(SUM(proceeds), 2)FROM ( SELECT CAST(t.start_time AS DATE) AS day, p.merchant_id, t.channel, 1 AS sales, t.charged_usd AS gross, 0 AS refunded, t.charged_usd * (1 - t.fee_rate) AS proceeds FROM transactions t JOIN products p ON p.id = t.product_id WHERE NOT t.is_trial AND NOT t.is_test AND t.channel <> 'promo' AND t.start_time >= TIMESTAMP '2026-09-01' AND t.start_time < TIMESTAMP '2026-09-30' UNION ALL SELECT CAST(t.refunded_at AS DATE), p.merchant_id, t.channel, 0, 0, t.charged_usd, -t.charged_usd * (1 - t.fee_rate) FROM transactions t JOIN products p ON p.id = t.product_id WHERE NOT t.is_trial AND NOT t.is_test AND t.channel <> 'promo' AND t.refunded_at >= TIMESTAMP '2026-09-01' AND t.refunded_at < TIMESTAMP '2026-09-30') AS mGROUP BY day, merchant_id, channelON CONFLICT (day, merchant_id, channel) DO UPDATESET sales = EXCLUDED.sales, gross_usd = EXCLUDED.gross_usd, refunds_usd = EXCLUDED.refunds_usd, net_usd = EXCLUDED.net_usd;
-- 3. The same load again, as a retried job would run it.INSERT INTO daily_merchant_revenue (day, merchant_id, channel, sales, gross_usd, refunds_usd, net_usd)SELECT day, merchant_id, channel, SUM(sales), SUM(gross), SUM(refunded), ROUND(SUM(proceeds), 2)FROM ( SELECT CAST(t.start_time AS DATE) AS day, p.merchant_id, t.channel, 1 AS sales, t.charged_usd AS gross, 0 AS refunded, t.charged_usd * (1 - t.fee_rate) AS proceeds FROM transactions t JOIN products p ON p.id = t.product_id WHERE NOT t.is_trial AND NOT t.is_test AND t.channel <> 'promo' AND t.start_time >= TIMESTAMP '2026-09-01' AND t.start_time < TIMESTAMP '2026-09-30' UNION ALL SELECT CAST(t.refunded_at AS DATE), p.merchant_id, t.channel, 0, 0, t.charged_usd, -t.charged_usd * (1 - t.fee_rate) FROM transactions t JOIN products p ON p.id = t.product_id WHERE NOT t.is_trial AND NOT t.is_test AND t.channel <> 'promo' AND t.refunded_at >= TIMESTAMP '2026-09-01' AND t.refunded_at < TIMESTAMP '2026-09-30') AS mGROUP BY day, merchant_id, channelON CONFLICT (day, merchant_id, channel) DO UPDATESET sales = EXCLUDED.sales, gross_usd = EXCLUDED.gross_usd, refunds_usd = EXCLUDED.refunds_usd, net_usd = EXCLUDED.net_usd;
-- 4. The late refund (given), then the load for that day only: [2026-09-22, 2026-09-23).UPDATE transactionsSET refunded_at = TIMESTAMP '2026-09-22 10:20:00', revenue_usd = 0WHERE transaction_id = 't_007681';
INSERT INTO daily_merchant_revenue (day, merchant_id, channel, sales, gross_usd, refunds_usd, net_usd)SELECT day, merchant_id, channel, SUM(sales), SUM(gross), SUM(refunded), ROUND(SUM(proceeds), 2)FROM ( SELECT CAST(t.start_time AS DATE) AS day, p.merchant_id, t.channel, 1 AS sales, t.charged_usd AS gross, 0 AS refunded, t.charged_usd * (1 - t.fee_rate) AS proceeds FROM transactions t JOIN products p ON p.id = t.product_id WHERE NOT t.is_trial AND NOT t.is_test AND t.channel <> 'promo' AND t.start_time >= TIMESTAMP '2026-09-22' AND t.start_time < TIMESTAMP '2026-09-23' UNION ALL SELECT CAST(t.refunded_at AS DATE), p.merchant_id, t.channel, 0, 0, t.charged_usd, -t.charged_usd * (1 - t.fee_rate) FROM transactions t JOIN products p ON p.id = t.product_id WHERE NOT t.is_trial AND NOT t.is_test AND t.channel <> 'promo' AND t.refunded_at >= TIMESTAMP '2026-09-22' AND t.refunded_at < TIMESTAMP '2026-09-23') AS mGROUP BY day, merchant_id, channelON CONFLICT (day, merchant_id, channel) DO UPDATESET sales = EXCLUDED.sales, gross_usd = EXCLUDED.gross_usd, refunds_usd = EXCLUDED.refunds_usd, net_usd = EXCLUDED.net_usd;
-- 5. The report reads only the table.SELECT merchant_id, channel, COUNT(*) FILTER (WHERE sales > 0) AS days_with_sales, SUM(sales) AS sales, SUM(gross_usd) AS gross_usd, SUM(refunds_usd) AS refunds_usd, SUM(net_usd) AS net_usdFROM daily_merchant_revenueWHERE day >= DATE '2026-09-01' AND day < DATE '2026-09-30'GROUP BY merchant_id, channelORDER BY merchant_id, channel;Expected output
| merchant_id | channel | days_with_sales | sales | gross_usd | refunds_usd | net_usd |
|---|---|---|---|---|---|---|
| mer_01 | north_market | 5 | 7 | 114.93 | 39.99 | 63.69 |
| mer_01 | south_market | 8 | 8 | 88.92 | 0.00 | 75.57 |
| mer_01 | web | 3 | 4 | 60.96 | 0.00 | 59.13 |
| mer_02 | north_market | 19 | 32 | 497.68 | 0.00 | 348.36 |
| mer_02 | south_market | 15 | 21 | 487.79 | 0.00 | 341.44 |
| mer_02 | web | 9 | 9 | 201.91 | 0.00 | 195.85 |
| mer_03 | north_market | 6 | 7 | 109.93 | 0.00 | 93.43 |
| mer_03 | south_market | 5 | 7 | 184.93 | 0.00 | 157.18 |
| mer_03 | web | 4 | 4 | 94.96 | 0.00 | 92.11 |
| mer_04 | north_market | 16 | 29 | 122.71 | 6.99 | 98.35 |
| mer_04 | south_market | 6 | 6 | 25.94 | 0.00 | 22.04 |
| mer_04 | web | 1 | 1 | 6.99 | 0.00 | 6.78 |
| mer_05 | north_market | 10 | 13 | 189.87 | 0.00 | 132.90 |
| mer_05 | south_market | 6 | 6 | 59.94 | 0.00 | 41.94 |
| mer_06 | north_market | 11 | 13 | 229.87 | 79.99 | 127.38 |
| mer_06 | south_market | 8 | 15 | 303.85 | 0.00 | 258.26 |
| mer_06 | web | 2 | 2 | 19.98 | 0.00 | 19.38 |
| mer_07 | north_market | 10 | 16 | 193.84 | 0.00 | 164.74 |
| mer_07 | south_market | 2 | 2 | 15.98 | 0.00 | 13.58 |
| mer_07 | web | 2 | 2 | 15.98 | 0.00 | 15.50 |
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. A data-modelling round: design a table for a report, fill it so that a rerun is safe, and query it. Reports then read ready totals: the rules for sales, refunds and fees live in one load, not in every report.
What to say. Three sentences, in this order, before any code:
- The grain: “One row per merchant, channel and UTC day. It’s a fact table: four additive measures by day, merchant and channel. Merchant names stay in merchants, the dimension.”
- The key: “The primary key is (day, merchant_id, channel), so the database refuses a second row for the same day, merchant and channel.”
- Idempotency: “The load replaces the rows of the days it loads. A rerun gives the same table, and a late refund only means loading its day again.”
Steps.
CREATE TABLEwith the grain as the primary key and money asNUMERIC(12,2).- The load: one list of rows from
transactionswithUNION ALL. Sales get the day ofstart_time; refunds get the day ofrefunded_atand a minus sign. Filter each branch to the range, thenGROUP BY day, merchant_id, channelandON CONFLICT (day, merchant_id, channel) DO UPDATE SET … = EXCLUDED.…. - The same statement twice more: the same range, then only 22 September after the given
UPDATE. - The report:
GROUP BY merchant_id, channelover the table, withCOUNT(*) FILTER (WHERE sales > 0).
The other load is DELETE of the range, then INSERT, inside BEGIN … COMMIT. It also removes a row whose day lost all its activity, which an upsert never does.
Traps.
- An upsert that adds,
SET sales = daily_merchant_revenue.sales + EXCLUDED.sales, is right for a balance (Duplicates and idempotency) and wrong here: every run adds the days again. mer_01 on north_market ends with 15 sales instead of 7. A load of totals overwrites. - A plain
INSERTwithout a key doubles every row on the second run. With the key, the second run stops with a duplicate-key error. Neither is safe to rerun. ON CONFLICT DO NOTHINGis safe to rerun, but it never corrects a row. After the late refund, mer_06 on north_market still shows 0.00 refunds instead of 79.99.- Refunds on the day of the sale: t_005659 was sold on 31 August and refunded on 17 September, so its refund drops out of September, and mer_01 on north_market shows 0.00 refunds instead of 39.99. A closed day would also change whenever an old sale is refunded.
- Rows built from sales, with a
LEFT JOINto refunds, lose the days that have refunds and no sales: 6 of the 319 rows. Start from both lists, withUNION ALLor aFULL JOINof the two totals. - A reload whose
DELETEhas no date range empties the table. After the reload of 22 September, the report has 10 rows instead of 35. Delete exactly the days you insert. - A sale is a paid transaction. With test purchases, mer_02 on south_market gets 22 sales instead of 21; trials add one sale to mer_01 on north_market; promo adds 3 rows.
- Round each row to cents;
NUMERIC(12,2)does it on insert. Without it, mer_01 on north_market sums to 63.699 instead of 63.69. - The range is half-open:
start_time >= '2026-09-01' AND start_time < '2026-09-30'.CAST(start_time AS DATE) BETWEEN '2026-09-01' AND '2026-09-30'also takes 30 September. No practice sale falls on that day, so it looks right. Check also runs your script on hidden edge-case data, which has sales during 30 September, and this version fails there. - In the report, a missing row means 0.
AVG(net_usd)over the table is the average of active days: 10.62 for mer_01 on north_market (6 rows), against 2.20 per calendar day (63.69 over 29 days).
Check. 35 rows. The table holds 319 rows, and 6 of them have refunds and no sales. The late refund moves mer_06 on north_market on 22 September from 22.08 to −45.91 net. The first report row is mer_01, north_market: 5 days with sales, 7 sales, 114.93 gross, 39.99 refunds, 63.69 net.
Follow-up. Each question has a short answer:
- “A refund arrives three days late. What do you do?” — Load its day again. A refund counts on its own day, so no other day changes. For late data in general, reload the last few days every night, and run a backfill for older days: the same load with an older range.
- “Do you reload all of September every night?” — No: an incremental load with a watermark. Store the newest change time you have loaded, and next time load only the days that changed after it. That needs a column such as
updated_at, whichtransactionsdoes not have: a refund changesrefunded_atin place. Without it, reload a window of days. - “The table grows for years. How do you store it?” — Partition by day or month (
PARTITION BY RANGE (day)). A reload replaces whole partitions, a monthly report reads one, and old ones move to cheap storage. - “Plan prices change. How do you report the price at the time of sale?” — A slowly changing dimension, type 2:
plan_prices (plan_id, price_usd, valid_from, valid_to), with a new row for each change. The join takes the row valid atstart_time. Herecharged_usdalready holds what was paid, so this table does not need it. - “What changes in a warehouse?” — The load becomes
MERGE INTO … USING (…) ON … WHEN MATCHED THEN UPDATE … WHEN NOT MATCHED THEN INSERT …, or, where the warehouse has it,INSERT OVERWRITEof the day’s partition. PostgreSQL hasMERGEtoo, since version 15, so it also works in this editor.
In production. A key that starts with day serves the reload and the date range of the report; a merchant’s dashboard wants an index on (merchant_id, day). The same table could feed Q12, but agree first where to round: summed over a month, the rounded days differ from Q12’s monthly rounding in 182 of the 192 merchant-channel months of January–August, by at most 0.07. A table that feeds other sums often keeps four decimals and rounds in the report.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.