Why JOINs Create Duplicate Rows (1-to-Many Explained)
JOINs multiply rows when one side has many matches. See why totals explode after joining order_items — and how to fix aggregates.
Not a bug — fan-out
One order can have many order_items. Join them and the order’s columns repeat once per line:
SELECT o.order_id, oi.product_id, oi.qty FROM orders o JOIN order_items oi ON o.order_id = oi.order_id;
If you then SUM a column from orders after joining line items, you can double-count — each order value repeats once per item.
-- Dangerous shape (fan-out then SUM on order fields) -- Prefer: aggregate order_items first, then JOIN
Symptom: inflated totals
Joining customers → orders → items and then COUNT(customers) counts customer rows once per item. Fix by aggregating the many-side first:
WITH items AS ( SELECT order_id, SUM(qty) AS units FROM order_items GROUP BY order_id ) SELECT o.order_id, items.units FROM orders o JOIN items ON items.order_id = o.order_id;
Checklist before you panic
- Is the relationship 1-to-many?
- Are you aggregating after the fan-out?
- Do you need
COUNT(DISTINCT …)or a pre-aggregate CTE?
Once you see multiplication as geometry, “mystery duplicates” become predictable.
FAQ
Why did my JOIN return duplicate rows?
One row on the left matched multiple rows on the right (one-to-many). That’s expected — aggregate in subqueries/CTEs before joining if you need one row per parent.
Try it yourself
The fastest way to lock this in is a short drill on the same Northstar Market tables.