skip to content

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:

sqldb=shop · session fan
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);
output, from postgres 18.6
#1 · ALTER TABLE
#2 · UPDATE 10000

now watch Ada's orders meet their lines:

query.sql
  1. 1SELECT o.id AS order_id, o.status, o.total
  2. 2FROM orders AS o
  3. 3WHERE o.customer_id = 42
  4. 4ORDER BY o.id;
order_idint4statustexttotalnumeric
880cancelled831.01
1455refunded720.05
6580delivered226.00
7787delivered351.96
8219delivered297.68
9615delivered90.17
9946placed516.26
(7 rows)
sum(o.total)
3033.13
right.

Ada's 7 orders, one row each, with the total stored on the order. they add up to 3,033.13.

query 1/3
real output, postgres 18.6 (PGlite 0.5.12) · fan-out
step through it. shaded bands are rows that share an 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

predict the output
sql
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:

sqldb=shop · session fan
continues session fan (1 earlier block run first)
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;
output, from postgres 18.6
#1 · SELECT 1
spentnumeric
3033.13
(1 row)
#2 · SELECT 1
spent_after_joinnumeric
8474.47
(1 row)

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:

sqldb=shop · session fan
continues session fan (2 earlier blocks run first)
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;
output, from postgres 18.6
SELECT 1
ordersint8distinct_ordersint8itemsint8
18743
(1 row)

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:

sqldb=shop · session fan
continues session fan (3 earlier blocks run first)
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;
output, from postgres 18.6
#1 · SELECT 1
right_answernumeric
9598.99
(1 row)
#2 · SELECT 1
after_joinnumericdistinct_after_joinnumeric
29014.959549.99
(1 row)

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.

hover a stage. the subquery turns 24,942 lines into one row per order, so the join to orders matches each order once.

a per-customer report that gets all three numbers right, for José and Ada:

sqldb=shop · session fan
continues session fan (4 earlier blocks run first)
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;
output, from postgres 18.6
SELECT 2
idint4nametextordersint8spentnumericitemsnumeric
6José Silva259598.99102
42Ada Lovelace73033.1343
(2 rows)

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:

order =
query.sql
  1. 1SELECT p.category, count(p.id) AS products, round(avg(p.price), 2) AS avg_price, sum(oi.qty) AS units
  2. 2FROM products AS p
  3. 3JOIN order_items AS oi ON oi.product_id = p.id
  4. 4GROUP BY p.category
  5. 5ORDER BY p.category NULLS FIRST;
the result for join, then aggregate
categorytextproductsint8avg_pricenumericunitsint8
null51254.51959
audio2714127.205130
bath2419107.244734
books155669.542946
games147082.832847
garden176174.133391
kitchen451867.748629
office292393.155611
outdoor234096.624364
pets2117112.474027
toys261289.694952
(11 rows)

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.

real output, postgres 18.6 (PGlite 0.5.12) · fan-out
switch the order of the two steps. after the join, 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?