UNION ALL and reconciliation
Some tasks need two sets of rows in one query. A cash-flow report stacks sales and refunds into one feed. A reconciliation puts two sources side by side and finds what is missing on either side. The wrong tool fails without an error: UNION drops equal amounts, a LEFT JOIN hides one side, and a filter in the wrong place removes the very rows the report is for.
UNION ALL: one row under another
Section titled “UNION ALL: one row under another”JOIN puts rows side by side: the result gets more columns. UNION ALL puts them one under another: the result gets more rows. Use it when two sets of rows describe the same kind of thing: sales and refunds, advances and repayments, events from two tables. Words in a task that point to it: cash flow, movements, sales and refunds, all events.
An example: the paid sales of prd_09 in September 2026 with a plus sign, and its refunds with a minus sign.
WITH movements AS ( SELECT 'sale' AS kind, start_time AS at, charged_usd AS amount FROM transactions WHERE product_id = 'prd_09' AND NOT is_test AND NOT is_trial AND channel <> 'promo' AND start_time >= TIMESTAMP '2026-09-01' AND start_time < TIMESTAMP '2026-10-01' UNION ALL SELECT 'refund', refunded_at, -charged_usd FROM transactions WHERE product_id = 'prd_09' AND NOT is_test AND NOT is_trial AND channel <> 'promo' AND refunded_at >= TIMESTAMP '2026-09-01' AND refunded_at < TIMESTAMP '2026-10-01')SELECT kind, COUNT(*) AS n, SUM(amount) AS usdFROM movementsGROUP BY kindORDER BY kind;| kind | n | usd |
|---|---|---|
| refund | 2 | -15.98 |
| sale | 15 | 329.85 |
The net total for September is SUM(amount) over the whole feed: 313.87.
Each branch has its own date
Section titled “Each branch has its own date”A sale belongs to the month of start_time. A refund belongs to the month of refunded_at. So each branch is a full SELECT with its own WHERE. Refund t_000482 shows why: the purchase was on 20 August, the refund on 2 September. The refund is in the September feed, and its sale is not. One shared filter on start_time would move this refund to August.
The rules of UNION ALL
Section titled “The rules of UNION ALL”- Columns match by position, not by name. Both branches need the same number of columns and compatible types. The names come from the first branch.
- A mistake here fails loudly. A missing column gives
each UNION query must have the same number of columns. Swapped columns giveinvalid input syntax for type numeric: "sale". ORDER BYandLIMITat the end apply to the whole result. A filter that is the same for both branches can go outside, on the feed. The first drill below does that withmonth.- A label column (
'sale','refund') lets you count each kind later.
Why not UNION
Section titled “Why not UNION”UNION without ALL removes equal rows from the whole result, as DISTINCT does. Here is the same feed with only the amount column:
| rows | sum | |
|---|---|---|
UNION ALL | 17 | 313.87 |
UNION | 3 | 49.99 |
The 15 sales are 10 at 7.99 and 5 at 49.99. UNION kept one row for each value: 7.99, 49.99 and −7.99. Money disappeared, and there was no error.
The rule: UNION ALL for money and events. Use UNION only for a list of unique values, for example every merchant_id that appears in two tables.
Why not JOIN
Section titled “Why not JOIN”A JOIN of the September sales with the September refunds on product_id returns 15 × 2 = 30 rows. Every sale is paired with every refund, and the sales add up to 659.70 instead of 329.85. There is no “this sale, this refund” link here. The report needs one feed, not pairs. Row multiplication explains this effect in detail.
Reconciliation: FULL OUTER JOIN
Section titled “Reconciliation: FULL OUTER JOIN”A reconciliation compares two sources by a key, when a row can be missing on either side: expected and received, our records and a bank statement, advances and the marketplace payouts that repay them. Words in a task: reconcile, compare, side by side, missing on either side.
LEFT JOIN keeps every row of the left side. FULL OUTER JOIN keeps every row of both sides and puts NULL where the pair is missing.
An example from the advances program. For every month with an advance, the channel payout for that month should arrive and cover what the merchant owes for it: the advance plus the fee. Here is mer_09, with payouts from May, so the months before the first advance are visible too.
WITH adv AS ( -- 1. each side down to the key SELECT channel, period_month, SUM(amount_usd + fee_usd) AS owed_usd FROM advances WHERE merchant_id = 'mer_09' GROUP BY channel, period_month),paid AS ( SELECT channel, period_month, SUM(amount_usd) AS paid_usd FROM channel_payouts WHERE merchant_id = 'mer_09' AND period_month >= DATE '2026-05-01' -- 2. filters inside the CTE GROUP BY channel, period_month)SELECT COALESCE(a.channel, p.channel) AS channel, -- 3. keys through COALESCE COALESCE(a.period_month, p.period_month) AS period_month, a.owed_usd, p.paid_usd, CASE WHEN p.channel IS NULL THEN 'missing' -- 4. one status per row WHEN a.channel IS NULL THEN 'unexpected' WHEN p.paid_usd < a.owed_usd THEN 'mismatch' ELSE 'ok' END AS statusFROM adv aFULL OUTER JOIN paid p ON p.channel = a.channel AND p.period_month = a.period_monthORDER BY period_month, channel;| channel | period_month | owed_usd | paid_usd | status |
|---|---|---|---|---|
| north_market | 2026-05-01 | NULL | 137.57 | unexpected |
| south_market | 2026-05-01 | NULL | 231.06 | unexpected |
| north_market | 2026-06-01 | 383.53 | 531.94 | ok |
| south_market | 2026-06-01 | 176.41 | 244.67 | ok |
| north_market | 2026-07-01 | 195.98 | 135.91 | mismatch |
| south_market | 2026-07-01 | 128.63 | 178.40 | ok |
| north_market | 2026-08-01 | 143.31 | NULL | missing |
| south_market | 2026-08-01 | 128.63 | 178.40 | ok |
How to read it:
- May, unexpected. The payouts came, but there was no advance yet: mer_09 joined the program on 16 June. From the program’s point of view, nothing repays here.
- July North Market, mismatch. The payout of 135.91 does not cover the 195.98 owed. Two advances were made for this month: a duplicate, which Q13 finds.
- August North Market, missing. An advance and no payout. North Market pays about 32 days after the month ends, so this payout is not due before October. A real report needs a “not due yet” status for it; Q12 has one.
Four rules
Section titled “Four rules”- Aggregate each side to the key first. mer_09 has two advances for July on North Market. Join the raw tables, and the one payout row meets both advances:
paid_usdbecomes 271.82, twice 135.91, and the mismatch disappears. - Take the keys through
COALESCE. In a row that exists only on the right,a.channelis NULL. WithoutCOALESCE, the May rows would have an emptychannel. - Check presence first, amounts second. A comparison with NULL is NULL, so
CASEfalls through toELSE. Without the twoIS NULLbranches, the missing and unexpected rows all come out as ‘ok’. When amounts come from different sources, compare with a tolerance, for exampleABS(a - b) > 1.00, not with<>. - Put the filters inside the CTEs. A condition on one side in
WHEREafter the join removes the rows where that side is missing. Move the payouts’ date filter toWHERE p.period_month >= DATE '2026-05-01', and 7 of the 8 rows remain: the missing August row is gone, and it is the row the reconciliation is for. ALEFT JOINfrom the advances is wrong for the same reason: 6 rows, and the May payouts disappear.
The same three-way split in Python is a set operation on dict keys: see Sets and duplicates.
Practice
Section titled “Practice”North Market cash flow per month in 2026 (January–September), test purchases excluded: a sale adds charged_usd * (1 - fee_rate) in the month of start_time; a refund subtracts the same amount in the month of refunded_at. Month as DATE, amount rounded to 2 decimals.
Output columns: month, cash_usdOrder: ORDER BY month
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
channel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)start_time— start of the period = time of purchase; "started in …" means this columncharged_usd— what the customer paid (gross)fee_rate— channel fee: 0.15 / 0.30 on the marketplaces, 0.03 on webrefunded_at— when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULLis_test— test purchase: exclude it from business numbers
| channel | start_time | charged_usd | fee_rate | refunded_at | is_test |
|---|---|---|---|---|---|
| north_market | 2025-01-01 04:48:03 | 79.99 | 0.3000 | NULL | false |
| north_market | 2025-01-01 02:08:33 | 6.99 | 0.1500 | NULL | false |
| north_market | 2025-01-22 14:37:00 | 39.99 | 0.1500 | 2025-02-04 15:18:13 | false |
"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
Show answer
Reference
WITH movements AS ( SELECT CAST(date_trunc('month', start_time) AS DATE) AS month, charged_usd * (1 - fee_rate) AS amount FROM transactions WHERE channel = 'north_market' AND NOT is_test UNION ALL SELECT CAST(date_trunc('month', refunded_at) AS DATE), -charged_usd * (1 - fee_rate) FROM transactions WHERE channel = 'north_market' AND NOT is_test AND refunded_at IS NOT NULL)SELECT month, ROUND(SUM(amount), 2) AS cash_usdFROM movementsWHERE month >= DATE '2026-01-01' AND month < DATE '2026-10-01'GROUP BY monthORDER BY month;Expected output
| month | cash_usd |
|---|---|
| 2026-01-01 | 3346.58 |
| 2026-02-01 | 2274.14 |
| 2026-03-01 | 2279.40 |
| 2026-04-01 | 2461.95 |
| 2026-05-01 | 2950.38 |
| 2026-06-01 | 2858.32 |
| 2026-07-01 | 3448.65 |
| 2026-08-01 | 3134.51 |
| 2026-09-01 | 2363.30 |
Sales and refunds are two feeds with the same columns: UNION ALL, then one GROUP BY month. Each branch computes its own month: start_time for a sale, refunded_at for a refund, which is why the refund branch keeps only rows with refunded_at IS NOT NULL. The date filter can sit outside the feed, on month, because both branches produce that column. UNION without ALL would merge two sales of the same amount in the same month into one row. Round once, after the SUM.
For mer_11, months May–August 2026: per (channel, period_month) show the advanced amount and the channel payout side by side, NULL where one side is missing.
Output columns: channel, period_month, advanced_usd, paid_usdOrder: ORDER BY period_month, channel
Tables, columns and how they connect
advances — advances: early payouts to merchants against marketplace payouts that have not arrived yet
merchant_id— → merchants.idchannel— which marketplace payout it is againstperiod_month— which sales month it is againstamount_usd— amount advanced (principal)
| merchant_id | channel | period_month | amount_usd |
|---|---|---|---|
| mer_01 | north_market | 2026-07-01 | 48.75 |
| mer_01 | north_market | 2026-08-01 | 96.34 |
| mer_01 | north_market | 2026-06-01 | 68.38 |
channel_payouts — what the partner marketplaces actually paid (Jan–Aug 2026)
merchant_id— → merchants.idchannel— north_market / south_marketperiod_month— first day of the sales month the payout is foramount_usd— payout amount
| merchant_id | channel | period_month | amount_usd |
|---|---|---|---|
| mer_01 | north_market | 2026-02-01 | 51.82 |
| mer_01 | north_market | 2026-03-01 | 57.76 |
| mer_01 | north_market | 2026-01-01 | 64.69 |
"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
Show answer
Reference
WITH adv AS ( SELECT channel, period_month, SUM(amount_usd) AS advanced_usd FROM advances WHERE merchant_id = 'mer_11' AND period_month >= DATE '2026-05-01' AND period_month < DATE '2026-09-01' GROUP BY channel, period_month),paid AS ( SELECT channel, period_month, SUM(amount_usd) AS paid_usd FROM channel_payouts WHERE merchant_id = 'mer_11' AND period_month >= DATE '2026-05-01' AND period_month < DATE '2026-09-01' GROUP BY channel, period_month)SELECT COALESCE(a.channel, p.channel) AS channel, COALESCE(a.period_month, p.period_month) AS period_month, a.advanced_usd, p.paid_usdFROM adv aFULL OUTER JOIN paid p ON p.channel = a.channel AND p.period_month = a.period_monthORDER BY period_month, channel;Expected output
| channel | period_month | advanced_usd | paid_usd |
|---|---|---|---|
| north_market | 2026-05-01 | NULL | 271.81 |
| south_market | 2026-05-01 | NULL | 171.98 |
| north_market | 2026-06-01 | 261.05 | 372.92 |
| south_market | 2026-06-01 | 177.19 | 253.12 |
| north_market | 2026-07-01 | 271.76 | NULL |
| south_market | 2026-07-01 | 156.35 | 223.35 |
| north_market | 2026-08-01 | 185.45 | NULL |
| south_market | 2026-08-01 | 144.43 | NULL |
A reconciliation of two sources, where a row can be missing on either side: FULL OUTER JOIN. Aggregate each side to (channel, period_month) in its own CTE, and filter the months inside both CTEs. Take the keys through COALESCE, otherwise a row that exists only on the right has NULL in channel. May has payouts and no advances. Three advances have no payout: July on North Market and August on both channels. A LEFT JOIN from either side loses one of these groups: from the advances it drops May, from the payouts it drops the three advances. Only FULL OUTER JOIN returns all 8 rows.
Further reading
Section titled “Further reading”- Combining queries —
UNION,INTERSECT,EXCEPT, and whyALLkeeps duplicates. - Joined tables —
FULL OUTER JOINand howONdiffers fromWHERE. - COALESCE — the first value that is not NULL.
- CASE — the branches are checked in order, and the first true one wins.
Related topics
Section titled “Related topics”- Row multiplication — why each side is aggregated to the key before the join.
- LEFT JOIN and zeros — the one-sided version, and why a right-table filter in
WHEREbreaks it. - Subqueries and CTE — one CTE per side keeps a reconciliation readable.
- Money and ledgers — the advances program and its ledger.
- Duplicates and idempotency — the unique key that stops a duplicate advance or payout.
- Money and reconciliation — Q12 and Q13 use both patterns of this page.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.