Part 05 / Topic 7 of 9
The two join pitfalls
Pitfall one: row multiplication. A join pairs every match with every match. Order 1 has two lines; join orders to order_items and order 1 appears twice — correct for line-level math, catastrophic if you then count "orders":
SELECT count(*) AS joined_rows,
count(DISTINCT o.order_id) AS actual_orders
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id;
joined_rows | actual_orders
-------------+---------------
13 | 9
(1 row)
13 joined rows, 9 real orders. Sum a per-order value (like a delivery fee) over those 13 rows and it's silently inflated. The discipline: know which table sets your row count ("one row per what?"), and reach for count(DISTINCT ...) or pre-aggregation (Part 6) when a join has fanned rows out.
Pitfall two: WHERE on a LEFT JOIN's right table. Filter the right side in WHERE and you delete the very NULL rows the LEFT JOIN kept:
SELECT c.first_name, o.order_id, o.status
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.status = 'delivered'
ORDER BY c.customer_id, o.order_id;
first_name | order_id | status
------------+----------+-----------
Asha | 1 | delivered
Asha | 3 | delivered
Ravi | 2 | delivered
Ravi | 6 | delivered
Meera | 8 | delivered
Sara | 9 | delivered
(6 rows)
Vikram vanished — NULL = 'delivered' isn't true — so this silently became an INNER JOIN. To keep everyone and only match delivered orders, the condition belongs in the ON:
SELECT c.first_name, o.order_id, o.status
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
AND o.status = 'delivered'
ORDER BY c.customer_id, o.order_id;
first_name | order_id | status
------------+----------+-----------
Asha | 1 | delivered
Asha | 3 | delivered
Ravi | 2 | delivered
Ravi | 6 | delivered
Meera | 8 | delivered
John | |
Sara | 9 | delivered
Vikram | |
(8 rows)
Rule: on an outer join, conditions about the kept side go in WHERE; conditions about the optional side go in ON.
🧪 Quick quiz — answer from memory, then check.
- You LEFT JOIN orders and add
WHERE o.status = 'delivered'. What happens to customers with no orders? - An order with 3 lines appears how many times in
orders JOIN order_items?
Show the answers
- They disappear — NULL status fails the WHERE, so the query behaves like an INNER JOIN. Put the condition in ON to keep them.
- 3 times — once per matching line. Per-order aggregates must account for that.
Done here? The practice set for Part 5 — 8 exercises with solutions — is on the part page.