Full answer
sql
CREATE TABLE ord (id INTEGER PRIMARY KEY, total INTEGER);
CREATE TABLE payments (order_id INTEGER, amount INTEGER);
CREATE TABLE shipments (order_id INTEGER, carrier TEXT);
INSERT INTO ord VALUES (1, 100), (2, 50);
INSERT INTO payments VALUES (1, 60), (1, 40), (2, 50);
INSERT INTO shipments VALUES (1, 'A'), (1, 'B'), (2, 'A');The query as written:
sql
SELECT SUM(o.total) AS revenue FROM ord o JOIN payments p ON p.order_id = o.id JOIN shipments s ON s.order_id = o.id;| revenue |
|---|
| 450 |
The query returns 450, but the true revenue is 150. Order 1 has two payments and two shipments, producing four joined rows that each carry total 100, so it contributes 400; order 2 contributes 50.
A corrected version:
sql
SELECT SUM(o.total) AS revenue, SUM(p.paid) AS paid, SUM(s.parcels) AS parcels
FROM ord o
LEFT JOIN (SELECT order_id, SUM(amount) AS paid FROM payments GROUP BY order_id) p ON p.order_id = o.id
LEFT JOIN (SELECT order_id, COUNT(*) AS parcels FROM shipments GROUP BY order_id) s ON s.order_id = o.id;| revenue | paid | parcels |
|---|---|---|
| 150 | 150 | 3 |
Each child table is collapsed to one row per order before joining, so every order is counted once: revenue 150, payments 150 and 3 parcels. The symptom, totals that grow when another join is added, is one of the most common reporting bugs; reconcile a new join by comparing the total with and without it. LEFT JOINs also keep orders that have no payments or shipments.
sql
CREATE TABLE ord (id INTEGER PRIMARY KEY, total INTEGER);
CREATE TABLE payments (order_id INTEGER, amount INTEGER);
CREATE TABLE shipments (order_id INTEGER, carrier TEXT);
INSERT INTO ord VALUES (1, 100), (2, 50);
INSERT INTO payments VALUES (1, 60), (1, 40), (2, 50);
INSERT INTO shipments VALUES (1, 'A'), (1, 'B'), (2, 'A');
SELECT SUM(o.total) AS revenue FROM ord o JOIN payments p ON p.order_id = o.id JOIN shipments s ON s.order_id = o.id;
SELECT SUM(o.total) AS revenue, SUM(p.paid) AS paid, SUM(s.parcels) AS parcels
FROM ord o
LEFT JOIN (SELECT order_id, SUM(amount) AS paid FROM payments GROUP BY order_id) p ON p.order_id = o.id
LEFT JOIN (SELECT order_id, COUNT(*) AS parcels FROM shipments GROUP BY order_id) s ON s.order_id = o.id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Two child joins multiply rows
- Aggregate children before joining
- Compare totals before and after each join
- LEFT JOIN keeps parents without children
Common mistakes
- Using SUM(DISTINCT) as a fix
- Joining several one-to-many tables directly
Follow-ups
- Why does SUM(DISTINCT total) fail as a repair?
- How would you detect a fan-out in a large query?
Tips
- Reconcile against a known total