Learning navigation

Code with Animation

Join Pitfalls: Duplicates & Fan-Out

See how joining two child tables multiplies rows, why NULL keys vanish, and how to spot a join that returns too many rows.

SQL5 min readConcept 18 of 44

More rows than you expect

A join makes one row for every matching pair. When a parent row has several children, the parent repeats, once per child. This growth is called fan-out.

Fan-out is harmless on its own. It becomes a bug when you join two child tables to the same parent: their counts multiply.

Wrong numbers that look right

A query with fan-out runs without an error and shows plausible rows. If you then add up order values, each order is counted several times and the total is wrong. Knowing the pattern is how you catch it.

Two child tables, one parent

SELECT c.name, o.id AS order_id, t.id AS ticket_id
FROM customers AS c
JOIN shop_orders AS o ON c.id = o.customer_id
JOIN tickets AS t ON c.id = t.customer_id;

Asha has 2 orders and 2 tickets, so she gets 2 x 2 = 4 rows. Ben has 1 order and 1 ticket, so he gets 1. The result has 5 rows. Each of Asha's orders appears twice, once per ticket, even though the two tables have nothing to do with each other.

The other trap is silent loss. Ticket 204 has a NULL customer_id. A NULL never matches in ON, so an INNER JOIN drops the ticket. Joining customers to tickets returns 3 rows, even though there are 4 tickets.

Watch the rows multiply

Run the three joins and compare the counts. In the last one, look at the rows marked as repeats, then try the DISTINCT patch.

SELECT c.name, o.id AS order_id
FROM customers AS c
INNER JOIN shop_orders AS o ON c.id = o.customer_id
ORDER BY c.id, o.id;
Result (3 rows)
nametextorder_idintegercheck
Asha101
Asha102
Ben103

Three orders, three rows. This is the count you expect: one row per order.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1A customer has 3 orders and 2 tickets. Joining customers to both tables gives how many rows for that customer?
  2. 2Four tickets exist, one with a NULL customer_id. `customers INNER JOIN tickets ON c.id = t.customer_id` returns only 3 rows. Why?
  3. 3You joined two child tables and some orders appear twice. What is the best fix?

Remember this

  • A join returns one row per matching pair, so a parent repeats once per child.
  • Two child tables joined to one parent multiply: 2 orders and 2 tickets make 4 rows.
  • A NULL key never matches, so those rows vanish from an INNER JOIN without a warning.
  • DISTINCT hides repeats but does not fix the cause. Predict the row count before you run a join.

Done with this concept?

Mark it complete to track your progress. No login needed.