Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 53/ 160
03. Joins & Relational Querying

Join Explosion / Fan-Out Bugs & How to Prevent Duplicate Counts

Spot fan-out that inflates aggregates and fix grain before counting.

AdvancedFan-out · Grain · Pre-agg3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

The inflated queryQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  o.id,3  SUM(p.amount) AS paid4FROM5  orders o6  JOIN order_items i ON i.order_id = o.id7  JOIN payments p ON p.order_id = o.id8GROUP BY9  o.id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative inflated payment total1 sample row
Representative inflated payment total
idpaid
5013000

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Pre-aggregate each side, then joinQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  items AS (3    SELECT4      order_id,5      COUNT(*) AS n_items6    FROM7      order_items8    GROUP BY9      order_id10  ),11  pay AS (12    SELECT13      order_id,14      SUM(amount) AS paid15    FROM16      payments17    GROUP BY18      order_id19  )20SELECT21  o.id,22  i.n_items,23  p.paid24FROM25  orders o26  LEFT JOIN items i ON i.order_id = o.id27  LEFT JOIN pay p ON p.order_id = o.id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/27
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative corrected order totals3 sample rows
Representative corrected order totals
idn_itemspaid
50131000
5022750
503NULLNULL

Note: Illustrative one-row-per-order results. NULLs show an order with no matching items or payments and are preserved by the LEFT JOINs.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Bring every table to the parent's grain before joining it.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

State the target grain

Decide what one output row should be (one per order) and which tables are one-to-many relative to it.

Focus at this step

one row per order

What to watch at this step
One-to-many
items, payments
Tip: use ← → to move between steps

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

Pre-aggregate, then join
Best for: Any query combining metrics from several one-to-many tables

Strengths: Correct sums and counts, and easy to reason about.

Watch out: More code, with one CTE per child table.

COUNT(DISTINCT child.id)
Best for: Fixing a count when you can't restructure the query

Strengths: Quick fix for counts.

Watch out: Doesn't work for sums or averages, and is expensive on big data.

Correlated subqueries in SELECT
Best for: Small result sets

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?
Interview tip: When a question involves several child tables, say "I'll pre-aggregate each one to the order grain before joining, to avoid fan-out" before writing SQL. It's the signal interviewers are looking for.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Filtering in ON Clause vs WHERE Clause in Outer Joins
Next topic
Semi-Joins & Anti-Joins (EXISTS, NOT EXISTS, IN, NOT IN Pitfalls with NULL)