JOIN: why rows multiply when tables meet
The orders table holds a region number; the region name lives in another table. A JOIN links them on that key. The idea is simple, but totals that inflate after a join are a common trap.
Rows attach only when keys match
A join condition compares columns with the same meaning. The usual shape is many rows on one side and one row on the other — many orders, one region. In that case the joined row count should equal the orders row count.
If the key types differ, nothing attaches and no error appears: the number 1 is not the text '1'. When a join returns zero rows, inspect both columns' types and a few sample values first.
SELECT o.order_id, o.revenue, r.region_name
FROM orders AS o
JOIN regions AS r ON o.region_id = r.region_id
LIMIT 10;
INNER versus LEFT
JOIN (INNER) keeps only rows matched on both sides. LEFT JOIN keeps every row of the left table and fills the right side with NULL when there is no match. "Show every order, leave the region blank if unknown" is a LEFT JOIN.
The choice changes the row count. If an INNER JOIN returns fewer rows than the base table, some rows have no match — which is itself a data-quality signal.
| Join | Rows kept | When unmatched |
|---|---|---|
| INNER JOIN | matched on both sides | dropped |
| LEFT JOIN | all left rows | right columns NULL |
| CROSS JOIN | every combination | not applicable (rows multiply) |
| SELF JOIN | the same table twice | aliases required |
Aggregating after a join
If you join first and sum second, an order matched to several rows in the other table is counted several times. Going the other way, a LEFT JOIN from regions leaves regions without orders as NULL rather than 0; COALESCE(SUM(o.revenue), 0) fixes the display.
The safe order is: check that the joined row count equals the base table, then aggregate.
SELECT r.region_name,
COUNT(o.order_id) AS orders,
COALESCE(SUM(o.revenue), 0) AS revenue
FROM regions AS r
LEFT JOIN orders AS o ON o.region_id = r.region_id
GROUP BY r.region_name
ORDER BY revenue DESC;
Chaining more than two tables
Three tables follow the same rule. When an intermediate table creates a second one-to-many link, rows multiply again. Pre-aggregate the many side in a subquery and join that instead; the row count becomes predictable.
Count rows before you join
Note both row counts before writing the join. More rows than the base table means a one-to-many link was traversed twice; fewer means unmatched rows were dropped. Those two numbers catch most join mistakes on their own.
Questions
Does a condition belong in ON or WHERE?
With INNER JOIN the result is the same. With LEFT JOIN it is not: ON decides what may attach, WHERE filters after attaching and can remove the NULL-extended rows.
Both tables have a column with the same name?
Qualify it with the table alias in SELECT. Leaving it unqualified raises an ambiguous-column error.
Sources
Every query in this guide runs against the built-in sample data.
Open the lab