In two sentences
A join puts rows from two tables side by side wherever their keys match. If a key appears more than once on one side, every match produces a row, so rows multiply and any total you compute afterwards grows with them.
See it
Three orders, two known customers:
| order_id | customer_id | amount |
|---|---|---|
| 1 | c1 | 100 |
| 2 | c2 | 50 |
| 3 | c9 | 30 |
| customer_id | country |
|---|---|
| c1 | FR |
| c2 | US |
- INNER JOIN keeps only matches: orders 1 and 2. Order 3 silently disappears, and so do its 30.
- LEFT JOIN keeps every order and fills the missing side with NULL: order 3 comes back with
country = NULL.
Now order 1 is paid in two instalments:
| order_id | payment |
|---|---|
| 1 | 60 |
| 1 | 40 |
| 2 | 50 |
Join orders to payments and order 1 appears twice. sum(o.amount) now says 100 + 100 + 50 = 250, not
150. Nothing errors. The number is just wrong. That is fan-out.
In SQL
Keep every order, add the country when we know it:
SELECT o.order_id, o.amount, c.country
FROM orders o
LEFT JOIN customers c ON c.customer_id = o.customer_id;Revenue and payments per order, without fan-out: aggregate the many side first, then join one row to one row.
WITH paid AS (
SELECT order_id, sum(payment) AS paid
FROM payments
GROUP BY order_id -- now one row per order_id
)
SELECT o.order_id, o.amount, coalesce(p.paid, 0) AS paid
FROM orders o
LEFT JOIN paid p ON p.order_id = o.order_id;Before trusting a join, check that the key you think is unique really is:
SELECT customer_id, count(*) FROM customers GROUP BY customer_id HAVING count(*) > 1;Common mistakes
- Filtering the right table in
WHEREafter a LEFT JOIN.WHERE c.country = 'FR'throws away the rows wherecountryis NULL, so the LEFT JOIN quietly becomes an INNER JOIN. Put the condition inONif you want to keep the unmatched rows. - Joining to a "dimension" that has history. A customers table with one row per customer per version fans out every order. Pick the version valid at the order's time, or the current one.
- Summing after joining two one-to-many tables. Orders × payments × shipments multiplies both. Aggregate each one to the order first.
- Comparing row counts only at the end. Count rows before and after each join while you build the query; a jump is the first sign of fan-out.
What an interviewer asks next
- "How would you know this join didn't duplicate rows?" Count before and after, and check the key is unique on the side you expect.
- "Order 3's customer is missing. Should it count in revenue by country?" Usually yes, in an
unknownbucket, so the total still matches finance.
Go further
The jOOQ article explains why Venn diagrams mislead about joins: a join is about matching rows, not about overlapping sets.
Practise it
Start with Enrich Orders with Customer Data, then Revenue by Category Without Double Counting (Bridge Table), which is fan-out in its purest form.