Follow the rows
One payment.
Counted twice.
A join can look right and still inflate a total. Change the records below, then follow each payment into the joined rows.
One synthetic account. Each payment is $10. Refunds of $1, $2, and $3 attach to the first payment. All events are posted; this example leaves out dates and currencies.
| ID | Amount |
|---|
| ID | Payment | Amount |
|---|
2. Inspect the join
Each refund matches its parent payment. Multiple matches repeat that payment in the result.
| Payment | Payment amount | Refund | Refund amount |
|---|
3. Compare the totals
DISTINCT payment amounts
Count each event once
Payments add; refunds subtract. Separate events keep separate identities.
See the signed events
| Event | Change |
|---|
Why the repair works
DISTINCT removes duplicate values. Two legitimate $10 payments are the same value, so it can discard a real payment. Combine events with UNION ALL instead: it preserves both.
Compare the three SQL queries
These queries use payments(id, amount_cents) and refunds(id, payment_id, amount_cents). All amounts are integer cents.
The inflated join
SELECT COALESCE(SUM(p.amount_cents), 0)
- COALESCE(SUM(r.amount_cents), 0) AS net_cents
FROM payments AS p
LEFT JOIN refunds AS r ON r.payment_id = p.id;
The incomplete DISTINCT patch
SELECT COALESCE(SUM(DISTINCT p.amount_cents), 0)
- COALESCE(SUM(r.amount_cents), 0) AS net_cents
FROM payments AS p
LEFT JOIN refunds AS r ON r.payment_id = p.id;
One row per event
WITH events AS (
SELECT amount_cents AS delta_cents FROM payments
UNION ALL
SELECT -amount_cents AS delta_cents FROM refunds
)
SELECT COALESCE(SUM(delta_cents), 0) AS net_cents
FROM events;
This is a JavaScript illustration of the displayed SQL, not a live SQL editor. It assumes valid event IDs and parent relationships. It does not handle reporting windows, currencies, duplicate ingestion, or a complete accounting ledger.
Implementation and verification
The calculation lives in a separate JavaScript model. A Python check runs the exact SQL shown above in SQLite and compares the results with that model: all 12 examples, 36 totals, and every intermediate joined row.
From the repository root, with Python 3 and Node.js installed, run:
python3 projects/sql-join-explorer/check.py
The check also covers seven invalid inputs and two hand-calculated examples. It uses no third-party packages or network calls.
Download the check script · Download the implementation notes