join fan-out
two one-to-many joins and your totals triple. aggregate first, then join.
- address
- everything.joins.fan_out
- part
- part 3, joins and subqueries
- chapter
- chapter 5 of 11
- reading time
- 7 min
joining a one-to-many table repeats the "one" side once per match. anything you then SUM, COUNT or AVG from the "one" side is counted again for every match: that's fan-out.
the fix is to aggregate first, then join: shrink the many side to one row per key before it meets the rest.
the picture
you know the report where revenue comes out nearly three times what finance says, and the query looks fine? every join in it is correct. the problem is what got summed after the joins.
think of a shopping bag with the receipt stapled to every item in it. count the receipts and you get the number of items. add up the totals printed on the receipts and you get the bag's total once per item. nobody lied: each receipt is real, there are just more copies of it than there were purchases.
the shop doesn't store an order's total on the order, but most real shops do, so add one. the total is computed from the order's lines, once:
ALTER TABLE orders ADD COLUMN total numeric(10,2);
UPDATE orders AS o
SET total = (SELECT sum(oi.qty * oi.unit_price) FROM order_items AS oi WHERE oi.order_id = o.id);now watch Ada's orders meet their lines:
- 1SELECT o.id AS order_id, o.status, o.total
- 2FROM orders AS o
- 3WHERE o.customer_id = 42
- 4ORDER BY o.id;
| order_idint4 | statustext | totalnumeric |
|---|---|---|
| 880 | cancelled | 831.01 |
| 1455 | refunded | 720.05 |
| 6580 | delivered | 226.00 |
| 7787 | delivered | 351.96 |
| 8219 | delivered | 297.68 |
| 9615 | delivered | 90.17 |
| 9946 | placed | 516.26 |
Ada's 7 orders, one row each, with the total stored on the order. they add up to 3,033.13.
order_id. after the join, each order's total sits in its band once per line, and the sum adds every copy. aggregating the lines first puts every order back in one row.order 880 has 3 lines, so its 831.01 is in the sum three times. your totals triple, line by line, and the bigger orders count the most.
the wrong total
SELECT sum(o.total)
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.customer_id = 42;both, for real:
SELECT sum(o.total) AS spent
FROM orders AS o
WHERE o.customer_id = 42;
SELECT sum(o.total) AS spent_after_join
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.customer_id = 42;| spentnumeric |
|---|
| 3033.13 |
| spent_after_joinnumeric |
|---|
| 8474.47 |
nothing in the second query is wrong on its own. the join is right: those are Ada's lines. the sum is right: it adds up the column. the mistake is the grain. after the join, a row means "one order line", and o.total is a fact about an order, so the sum counts order facts at line grain.
two one-to-many joins
chain two of them, customers → orders → order_items, and every level above the last join gets repeated. Ada's name is in 18 rows, each order in as many rows as it has lines. counting orders by counting rows goes wrong the same way:
SELECT count(o.id) AS orders, count(DISTINCT o.id) AS distinct_orders, sum(oi.qty) AS items
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
JOIN order_items AS oi ON oi.order_id = o.id
WHERE c.id = 42;| ordersint8 | distinct_ordersint8 | itemsint8 |
|---|---|---|
| 18 | 7 | 43 |
count(o.id) says 18, because it counts lines. count(DISTINCT o.id) says 7, which is right, and sum(oi.qty) is right too, because qty is a fact about a line, and the rows are lines.
so DISTINCT fixes counts. it does not fix sums. sum(DISTINCT o.total) adds up the distinct values, and two different orders can have the same total. José Silva (customer 6) has two orders of 49.00 each:
SELECT sum(o.total) AS right_answer
FROM orders AS o
WHERE o.customer_id = 6;
SELECT sum(o.total) AS after_join, sum(DISTINCT o.total) AS distinct_after_join
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.customer_id = 6;| right_answernumeric |
|---|
| 9598.99 |
| after_joinnumeric | distinct_after_joinnumeric |
|---|---|
| 29014.95 | 9549.99 |
9,598.99 is what José spent. the join makes it 29,014.95. DISTINCT makes it 9,549.99, exactly 49.00 short, because one of the two 49.00 orders got thrown away as a duplicate. there's no keyword that un-fans a sum.
aggregate first, then join
the fix that always works: bring the many side down to one row per key before the join. then every join is one-to-one or many-to-one, and nothing gets repeated.
hover a stage.
a per-customer report that gets all three numbers right, for José and Ada:
SELECT c.id, c.name, count(*) AS orders, sum(o.total) AS spent, sum(li.items) AS items
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
JOIN (SELECT order_id, sum(qty) AS items
FROM order_items
GROUP BY order_id) AS li ON li.order_id = o.id
WHERE c.id IN (6, 42)
GROUP BY c.id
ORDER BY c.id;| idint4 | nametext | ordersint8 | spentnumeric | itemsnumeric |
|---|---|---|---|---|
| 6 | José Silva | 25 | 9598.99 | 102 |
| 42 | Ada Lovelace | 7 | 3033.13 | 43 |
the (SELECT ... GROUP BY order_id) AS li is a subquery used as a table, a derived table. a CTE says the same thing with a name up front, which reads better once there are two of them.
the quiet one: averages
a sum that triples is easy to spot. an average that's off by a quarter isn't. here's a category report, one join and three numbers about products:
- 1SELECT p.category, count(p.id) AS products, round(avg(p.price), 2) AS avg_price, sum(oi.qty) AS units
- 2FROM products AS p
- 3JOIN order_items AS oi ON oi.product_id = p.id
- 4GROUP BY p.category
- 5ORDER BY p.category NULLS FIRST;
| categorytext | productsint8 | avg_pricenumeric | unitsint8 |
|---|---|---|---|
| null | 512 | 54.51 | 959 |
| audio | 2714 | 127.20 | 5130 |
| bath | 2419 | 107.24 | 4734 |
| books | 1556 | 69.54 | 2946 |
| games | 1470 | 82.83 | 2847 |
| garden | 1761 | 74.13 | 3391 |
| kitchen | 4518 | 67.74 | 8629 |
| office | 2923 | 93.15 | 5611 |
| outdoor | 2340 | 96.62 | 4364 |
| pets | 2117 | 112.47 | 4027 |
| toys | 2612 | 89.69 | 4952 |
one join, three columns from the products side, one from order_items. the counts are line counts, the averages are weighted by sales, and only units is right.
products counts order lines, avg_price is weighted by how often each product sold, and only units is right. kitchen's average drops from 88.62 to 67.74, and nothing about it looks wrong.4,518 kitchen "products" is absurd enough that someone would notice. 67.74 as the average kitchen price is not. it's the average price of a thing sold, cheap best sellers counted once per order line, which is a real number, just not the one the column header promises. fan-out bends every aggregate over the "one" side: count, sum and average alike.
(the fixed version uses a LEFT JOIN, so the left-handed teapot, which never sold, still counts as a kitchen product: 19.)
keylines
- a one-to-many join repeats the "one" side once per match.
- sums, counts and averages over the repeated side come out inflated or skewed.
- count(DISTINCT key) fixes a count. nothing like it fixes a sum.
- aggregate the many side to one row per key first, then join.
- check the grain: is the key you sum by still unique after the joins?