Join Explosion / Fan-Out Bugs & How to Prevent Duplicate Counts
Spot fan-out that inflates aggregates and fix grain before counting.
In plain words
If one row matches many rows, it gets copied. Add up the copies and your totals come out too big.
Think of it like…
Counting wedding guests by joining the guest list to both the meal choices and the gift list: a guest who chose 2 meals and brought 3 gifts shows up 6 times, and your headcount is wildly off.
Where you’ve seen it
SELECT o.id, SUM(p.amount), COUNT(i.id) FROM orders o JOIN order_items i ON i.order_id = o.id JOIN payments p ON p.order_id = o.id GROUP BY o.id: an order with 3 items and 2 payments produces 6 rows, so payments are summed 3 times over and items counted twice over.
Words you’ll hear
- Grain
- What one row represents: one order, one order item, one payment.
- Fan-out
- A row duplicated because it matches several rows in a joined table.
- Pre-aggregation
- Grouping a one-to-many table down to the parent's grain before joining.
- Chasm trap
- The data-modelling name for joining one parent to two independent one-to-many children.
Visual diagram
Theory & example queries
Why the numbers go wrong
A join produces one output row per matching pair. Order to items is one-to-many, so each order row is repeated once per item. Joining payments as well repeats every one of those rows once per payment, so each order appears items × payments times, and every amount is summed that many times.
COUNT(DISTINCT i.id) can rescue a count, but there's no equivalent for sums: SUM(DISTINCT p.amount) adds each distinct value once, so two genuine ₹500 payments are counted as one. The only reliable fix is to change the grain before aggregating.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
SELECT o.id, SUM(p.amount) AS paidFROM orders o JOIN order_items i ON i.order_id = o.id JOIN payments p ON p.order_id = o.idGROUP BY o.id;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative inflated payment total1 sample row
| id | paid |
|---|---|
| 501 | 3000 |
Note: Assumes order 501 has three items and two payments of 500 each. The two-many-to-many join paths produce six payment rows, inflating 1,000 to 3,000.
For 3 items and two ₹500 payments it reports ₹3,000 paid instead of ₹1,000.
Key takeaway: Rows multiply across one-to-many joins; sums multiply with them.
Fixing the grain
Aggregate each one-to-many table down to one row per parent key in its own subquery or CTE, then join those results to the parent. Each join is now one-to-one, so nothing multiplies.
Make it a habit to check the grain: count rows before and after each join, and test uniqueness of the key you think you're at with GROUP BY key HAVING COUNT(*) > 1. Analytics tools such as dbt encode the same idea as uniqueness tests on model keys.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
WITH items AS ( SELECT order_id, COUNT(*) AS n_items FROM order_items GROUP BY order_id ), pay AS ( SELECT order_id, SUM(amount) AS paid FROM payments GROUP BY order_id )SELECT o.id, i.n_items, p.paidFROM orders o LEFT JOIN items i ON i.order_id = o.id LEFT JOIN pay p ON p.order_id = o.id;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative corrected order totals3 sample rows
| id | n_items | paid |
|---|---|---|
| 501 | 3 | 1000 |
| 502 | 2 | 750 |
| 503 | NULL | NULL |
Note: Illustrative one-row-per-order results. NULLs show an order with no matching items or payments and are preserved by the LEFT JOINs.
Key takeaway: Bring every table to the parent's grain before joining it.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
State the target grain
Decide what one output row should be (one per order) and which tables are one-to-many relative to it.
one row per order
When to use it & trade-offs
What it is
Fan-out happens when a join matches one row to several rows on the other side, multiplying it. Joining a table to *two* one-to-many tables at once multiplies rows by both, so SUM() and COUNT() silently report inflated numbers. The fix is to bring each side to the right grain (usually by aggregating it first) before joining.
Why it matters: It's the most common cause of "the dashboard says revenue doubled" bugs, and it produces no error, just believable wrong numbers. Senior data and analytics interviews almost always include a question that tests whether you notice it.
When to reach for it
- Order reports that combine items, payments, refunds or shipments
- User metrics that combine sessions, purchases and support tickets
- Any query where the join path goes through more than one one-to-many relationship
When to avoid or be careful
- Joining a parent to two child tables and aggregating in one step
- Patching inflated sums with SUM(DISTINCT …)
- Shipping a metric without checking the row count at the target grain
Ways to deal with fan-out
Strengths: Correct sums and counts, and easy to reason about.
Watch out: More code, with one CTE per child table.
Strengths: Quick fix for counts.
Watch out: Doesn't work for sums or averages, and is expensive on big data.
Strengths: Each metric computed per parent row with no fan-out.
Watch out: Can be slow over many rows.
Interview signals & numbers to know
When this topic comes up
- “Revenue in the dashboard doubled overnight”
- “Why are my sums too high after the join?”
- Joining to several child tables
- Grain
- COUNT(*) vs COUNT(DISTINCT id) mismatch
Benchmarks & rules of thumb
- items × payments
- rows per order after joining both
- 1
- row per parent: the target after pre-aggregation
- 0
- error messages fan-out produces
Common mistakes & follow-ups
Common interview mistakes
- Joining orders to items and payments together and summing payments.
- Using SUM(DISTINCT amount), which merges genuinely equal payments.
- Switching from INNER to LEFT JOIN to "fix" totals, which doesn't change fan-out at all.
Likely interviewer follow-ups
- How do you detect fan-out in a query you didn't write?
- Why doesn't SUM(DISTINCT …) fix an inflated sum?
- How would you compute revenue and item count per customer from orders, items and payments correctly?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Join Explosion / Fan-Out Bugs & How to Prevent Duplicate Counts with hands-on SQL practice and interview Q&A.