Skip to content

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.

SQLQ11 · Difficulty: easy · Target time: 8 min

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.

  1. Which copy is the real one?

    The first by received_at. The others are duplicates.

  2. Is a duplicate an exact copy of the event?

    Yes: same event_id, type and occurred_at; only received_at differs.

  3. Which day?

    The day of occurred_at (UTC), from 2026-09-01 to 2026-09-29.

  4. 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_at
FROM webhook_events
WHERE event_id = 'evt_000834'
ORDER BY received_at;
event_idtypeoccurred_atreceived_at
evt_000834renewal2026-09-06 22:50:132026-09-06 22:50:40
evt_000834renewal2026-09-06 22:50:132026-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.

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 duplicates
FROM ranked
WHERE occurred_at >= TIMESTAMP '2026-09-01'
AND occurred_at < TIMESTAMP '2026-09-30'
GROUP BY 1, 2
ORDER BY day, type;

Expected output

daytypeeventsduplicates
2026-09-01expiration70
2026-09-01purchase31
2026-09-01refund10
2026-09-01renewal170
2026-09-02expiration30
2026-09-02purchase60
2026-09-02refund10
2026-09-02renewal40
2026-09-03expiration50
2026-09-03purchase60
2026-09-03renewal141
2026-09-04expiration30
2026-09-04purchase41
2026-09-04renewal61
2026-09-05expiration50
2026-09-05purchase70
2026-09-05renewal181
2026-09-06expiration20
2026-09-06purchase51
2026-09-06renewal102
87 rows (first 20 shown)
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.

  1. Number the copies of each event before grouping: ROW_NUMBER() OVER (PARTITION BY event_id ORDER BY received_at). rn = 1 is the event, rn > 1 is a duplicate.
  2. GROUP BY the day of occurred_at and the type, with COUNT(*) FILTER (WHERE rn = 1) and COUNT(*) FILTER (WHERE rn > 1).

Traps.

  • The day is the day of occurred_at, when the event happened, not of received_at. In the practice data every copy of a September event arrives on the day the event happened, so grouping by received_at looks 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”
SQLQ12 · Difficulty: hard · Target time: 30 min

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.

  1. Test purchases?

    Excluded.

  2. Expected proceeds of 0 or less, when refunds are bigger than sales?

    Ignore those: nothing is expected for that month.

  3. Only one side exists. What goes in expected_usd or paid_usd?

    NULL, not 0: it shows which side is missing.

  4. 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.

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 s
WHERE status <> 'matched' -- not "NOT (payouts = 1 AND ...)": NULL would drop the missing rows
ORDER BY merchant_id, channel, period_month;

Expected output

merchant_idchannelperiod_monthexpected_usdpaid_usdstatus
mer_01north_market2026-01-0157.7664.69mismatch
mer_01north_market2026-04-0117.8215.15mismatch
mer_01north_market2026-08-01137.62NULLnot_due_yet
mer_01south_market2026-08-0141.59NULLmissing_payout
mer_02north_market2026-02-01328.10NULLmissing_payout
mer_02north_market2026-05-01369.39NULLmissing_payout
mer_02north_market2026-06-01363.75727.50duplicate_payout
mer_02north_market2026-08-01347.64NULLnot_due_yet
mer_02south_market2026-07-01272.10NULLmissing_payout
mer_03north_market2026-03-0125.4521.63mismatch
mer_03north_market2026-08-01161.43NULLnot_due_yet
mer_04north_market2026-04-0166.1556.23mismatch
mer_04north_market2026-08-01238.60NULLnot_due_yet
mer_05north_market2026-05-01132.91142.21mismatch
mer_05north_market2026-08-01118.90NULLnot_due_yet
mer_06north_market2026-04-01102.7792.49mismatch
mer_06north_market2026-08-01463.92NULLnot_due_yet
mer_06south_market2026-01-01210.66NULLmissing_payout
mer_07north_market2026-06-01120.57135.04mismatch
mer_07north_market2026-08-01146.06NULLnot_due_yet
32 rows (first 20 shown)
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.

  1. movements: sales and refunds with a minus sign in one feed (UNION ALL). A sale counts in the month of start_time, a refund in the month of refunded_at.
  2. expected per (merchant, channel, month), rounded, above 0 only.
  3. paid from channel_payouts: the sum and the number of rows.
  4. FULL OUTER JOIN on all three keys, with COALESCE for the key columns.
  5. A CASE with the statuses in priority order. Keep every row that is not ‘matched’.

Traps.

  • You need a FULL JOIN: either side can be missing. A LEFT JOIN from expected loses a payout that nobody expected. The practice data has none, but the hidden edge-case data that Check also uses has one, and the CASE must 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 the HAVING that 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).

SQLQ13 · Difficulty: hard · Target time: 15 min

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.

  1. One row per advance?

    One row per broken rule.

  2. No expected proceeds for that month?

    Treat them as 0.

  3. 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.

  4. 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.

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_limit
UNION ALL
SELECT advance_id, merchant_id, 'before_enrollment' FROM checked WHERE before_enrollment
UNION ALL
SELECT advance_id, merchant_id, 'duplicate' FROM checked WHERE duplicate
ORDER BY advance_id, issue;

Expected output

advance_idmerchant_idissue
adv_0007mer_03before_enrollment
adv_0024mer_07over_limit
adv_0028mer_09duplicate
3 rows
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.

  1. expected as in Q12, without the date filter.
  2. checked: one row per advance with three boolean flags.
  3. UNION ALL over the flags: one output row per broken rule.

Traps.

  • An advance can have no expected proceeds. Use a LEFT JOIN and COALESCE(e.expected_usd, 0). An inner join drops the advance with all its flags, and without COALESCE the limit is NULL, so over_limit is 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; with amount_usd > 0.70 * expected and no ROUND, 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 the IS NULL branch.
  • 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 a created_at. GROUP BY idempotency_key HAVING COUNT(*) > 1 would 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.

SQLQ14 · Difficulty: medium · Target time: 12 min

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.

  1. Ledger signs?

    advance and fee entries are positive; repayment entries are negative. The balance is the sum.

  2. Open advance?

    An advance_id whose entries sum to more than 0.

  3. As of when?

    Entries with created_at < 2026-09-30.

  4. Which merchants?

    Only those who owe more than 0.

  5. 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.

  6. "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_at
FROM ledger_entries
WHERE advance_id = 'adv_0001'
ORDER BY created_at, entry_id;
entry_idmerchant_idadvance_identry_typeamount_usdcreated_at
le_00001mer_01adv_0001advance68.382026-07-02 10:00:00
le_00002mer_01adv_0001fee2.052026-07-02 10:00:00
le_00003mer_01adv_0001repayment-70.432026-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.

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_on
FROM per_advance
GROUP BY merchant_id
HAVING SUM(outstanding_usd) > 0
ORDER BY outstanding_usd DESC, merchant_id;

Expected output

merchant_idoutstanding_usdopen_advancesoldest_open_advance_on
mer_11619.6832026-08-02
mer_09241.3022026-08-02
mer_04172.0312026-09-02
mer_01129.2122026-09-02
mer_03116.3912026-09-02
mer_07105.3112026-09-02
6 rows
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.

  1. A CTE per_advance: GROUP BY merchant_id, advance_id → the sum of the entries and the date of the advance entry.
  2. Per merchant: SUM, COUNT(*) FILTER (WHERE outstanding_usd > 0), MIN(advanced_at) FILTER (WHERE outstanding_usd > 0), and HAVING 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 MIN over 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_at of its advance entry: MIN(created_at) FILTER (WHERE entry_type = 'advance'). The task promises that the fee has the same time and repayments come later, so a plain MIN gives 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”
SQLQ15 · Difficulty: hard · Target time: 25 min

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.

  1. Which time zone defines the day?

    UTC: every timestamp in the data is UTC.

  2. 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.

  3. 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.

  4. 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_rate
FROM transactions t
JOIN products p ON p.id = t.product_id
WHERE t.transaction_id IN ('t_005659', 't_007681')
ORDER BY t.start_time;
idmerchant_idchannelstart_timerefunded_atcharged_usdfee_rate
t_005659mer_01north_market2026-08-31 07:09:582026-09-17 06:25:4439.990.1500
t_007681mer_06north_market2026-09-15 04:56:52NULL79.990.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.

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 m
GROUP BY day, merchant_id, channel
ON CONFLICT (day, merchant_id, channel) DO UPDATE
SET 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 m
GROUP BY day, merchant_id, channel
ON CONFLICT (day, merchant_id, channel) DO UPDATE
SET 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 transactions
SET refunded_at = TIMESTAMP '2026-09-22 10:20:00', revenue_usd = 0
WHERE 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 m
GROUP BY day, merchant_id, channel
ON CONFLICT (day, merchant_id, channel) DO UPDATE
SET 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_usd
FROM daily_merchant_revenue
WHERE day >= DATE '2026-09-01' AND day < DATE '2026-09-30'
GROUP BY merchant_id, channel
ORDER BY merchant_id, channel;

Expected output

merchant_idchanneldays_with_salessalesgross_usdrefunds_usdnet_usd
mer_01north_market57114.9339.9963.69
mer_01south_market8888.920.0075.57
mer_01web3460.960.0059.13
mer_02north_market1932497.680.00348.36
mer_02south_market1521487.790.00341.44
mer_02web99201.910.00195.85
mer_03north_market67109.930.0093.43
mer_03south_market57184.930.00157.18
mer_03web4494.960.0092.11
mer_04north_market1629122.716.9998.35
mer_04south_market6625.940.0022.04
mer_04web116.990.006.78
mer_05north_market1013189.870.00132.90
mer_05south_market6659.940.0041.94
mer_06north_market1113229.8779.99127.38
mer_06south_market815303.850.00258.26
mer_06web2219.980.0019.38
mer_07north_market1016193.840.00164.74
mer_07south_market2215.980.0013.58
mer_07web2215.980.0015.50
35 rows (first 20 shown)
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:

  1. 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.”
  2. The key: “The primary key is (day, merchant_id, channel), so the database refuses a second row for the same day, merchant and channel.”
  3. 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.

  1. CREATE TABLE with the grain as the primary key and money as NUMERIC(12,2).
  2. The load: one list of rows from transactions with UNION ALL. Sales get the day of start_time; refunds get the day of refunded_at and a minus sign. Filter each branch to the range, then GROUP BY day, merchant_id, channel and ON CONFLICT (day, merchant_id, channel) DO UPDATE SET … = EXCLUDED.….
  3. The same statement twice more: the same range, then only 22 September after the given UPDATE.
  4. The report: GROUP BY merchant_id, channel over the table, with COUNT(*) 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 INSERT without 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 NOTHING is 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 JOIN to refunds, lose the days that have refunds and no sales: 6 of the 319 rows. Start from both lists, with UNION ALL or a FULL JOIN of the two totals.
  • A reload whose DELETE has 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, which transactions does not have: a refund changes refunded_at in 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 at start_time. Here charged_usd already 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 OVERWRITE of the day’s partition. PostgreSQL has MERGE too, 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.