Join pitfalls and the grain problem
The previous lesson was about rows that go missing. This one is about rows that multiply, which is worse, because a missing row is usually noticed and a duplicated one quietly inflates a total.
If you take one thing from this track into a code review, take this: ask what one row of the result means. That question has a name — the grain — and most join bugs are a grain the author did not intend.
A query that returns twice the money
Carol has three sales. Count her employee row once:
SELECT count(*) AS employees FROM employee WHERE department_id = 2;
Two — Carol and Dan. Now join sales in and count again:
SELECT count(*) AS rows_returned
FROM employee e
JOIN sale s ON s.employee_id = e.id
WHERE e.department_id = 2;
Five. The grain changed from one row per employee to one row per sale. That is not a bug by itself — it is what a join does — but it becomes one the moment you aggregate something from the employee side:
SELECT sum(e.salary) AS total_salary
FROM employee e
JOIN sale s ON s.employee_id = e.id
WHERE e.department_id = 2;
455001.25. The real salary bill for Sales is 182000.50. Carol’s salary was
counted three times and Dan’s twice, because each appears once per sale. The
query is syntactically fine, runs without warning, and is wrong by a factor of
two and a half.
Why DISTINCT is not the fix
The instinct is to reach for DISTINCT:
SELECT sum(DISTINCT e.salary) AS total_salary
FROM employee e
JOIN sale s ON s.employee_id = e.id
WHERE e.department_id = 2;
91000.25. Now it is wrong the other way. Carol and Dan earn the same
salary, so DISTINCT collapsed two legitimately separate values into one.
This is the trap behind the trap. DISTINCT deduplicates values, and the
thing you wanted to deduplicate was entities. They coincide often enough that
SELECT DISTINCT appears to fix fan-out in testing and then fails on the first
tie in production. A tie is not exotic — two employees on the same salary, two
orders for the same amount, two events in the same millisecond.
The fix: aggregate first, then join
Collapse the many-side to one row per key before joining, so the join is one-to-one and the grain is what you meant:
SELECT d.name AS department,
sum(e.salary) AS total_salary,
coalesce(sum(s.total), 0) AS total_sales
FROM employee e
JOIN department d ON d.id = e.department_id
LEFT JOIN (
SELECT employee_id, sum(amount) AS total
FROM sale
GROUP BY employee_id
) s ON s.employee_id = e.id
WHERE e.department_id = 2
GROUP BY d.name;
One row per department, salary counted once per employee, sales summed
correctly. The subquery’s grain is one row per employee, which matches the
grain of employee, so joining them multiplies nothing.
The same shape reads better as a CTE, which is the next part of the track.
The other direction: a join that silently filters
Fan-out multiplies rows. A join against a table that is missing keys removes
them, and INNER is the default:
SELECT e.name, sum(s.amount) AS sales
FROM employee e
JOIN sale s ON s.employee_id = e.id
GROUP BY e.name
ORDER BY e.name;
Three rows. Alice, Bob, Erin and Frank have no sales and have vanished from a
report that reads like it covers everyone. LEFT JOIN with a coalesce is
usually what was meant:
SELECT e.name, coalesce(sum(s.amount), 0) AS sales
FROM employee e
LEFT JOIN sale s ON s.employee_id = e.id
GROUP BY e.name
ORDER BY e.name;
Seven rows, four of them zero. Note the coalesce is around sum, not inside
it: sum over no rows returns NULL, not 0, and a NULL in a revenue column
is the kind of thing that reaches a dashboard.
How to spot it in review
Three questions, in order:
- What is the grain of each table in the
FROM? One row per employee? One per sale? Per employee per day? - Does any join have a many-side? If the
ONclause is not matching a unique key on at least one side, rows multiply. - Is anything from the one-side being aggregated? A
sum,countoravgover a column from the one-side of a one-to-many join is the bug.
If all three line up badly, the result is inflated and nothing will say so.
Try it
Run the sum(e.salary) pair in the
SQL playground and watch 182000.50 become
455001.25. The drill is
Revenue and headcount per department, whose
two aggregates over sibling tables inflate each other, and where DISTINCT
repairs the count while corrupting the sum.
Fan-out is also why denormalised stores pre-join their data and accept the duplication deliberately — see SQL vs NoSQL.
Interview questions
1. What does “grain” mean, and why does it matter in a join? The grain is what one row of a result represents. A join between tables of different grain multiplies rows, so any aggregate over the coarser side is computed more than once.
2. A report sums salaries and comes out roughly double. What is the first thing you check? Whether a one-to-many join is in the query — one row per employee becoming one row per sale or per order — and whether the aggregate is over the one-side.
3. Why is SELECT DISTINCT the wrong fix for fan-out?
It deduplicates values, not entities. Two rows that are legitimately distinct
but hold the same value collapse into one, so the total becomes too small
instead of too large. It fails on the first tie.
4. How do you aggregate across two one-to-many relationships from the same table without double counting? Aggregate each to its own key in separate subqueries or CTEs, then join those, so every join is one-to-one. Joining both detail tables directly multiplies one by the other.
5. Why does sum() over no rows return NULL rather than 0?
Because there is nothing to add, and the standard distinguishes “no value” from
“zero”. count() returns 0 because counting nothing is a well-defined zero.
Wrap the sum in coalesce when a numeric default is wanted.
6. You add a LEFT JOIN to an existing report and the row count goes up. Is
that a bug?
Possibly not, but it means the right table has multiple matches per left row.
A LEFT JOIN never drops left rows, so an increase is always fan-out, and every
pre-existing aggregate in the query is now suspect.
Next
NULLs in joins and filters — three-valued
logic, and the NOT IN that returns nothing at all.