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.
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.
| nametext | order_idinteger | check |
|---|---|---|
| Asha | 101 | |
| Asha | 102 | |
| Ben | 103 |
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.
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.