Skip to content

Joins, drawn row by row

BasicsUnder the hood

Venn diagrams make joins look like set overlaps, then a join returns more rows than either table has. Draw a join instead as rows from one table matched against rows from the other, and inner, left and full joins each become one simple rule.

01 Two small tables

Three users and four orders. Each order stores the id of the user who placed it. Ben has placed nothing, and the mug belongs to user 4, who has been deleted.

setup.sql
CREATE TABLE users (id int PRIMARY KEY, name text);
CREATE TABLE orders (item text, user_id int);
INSERT INTO users VALUES (1, 'Ana'), (2, 'Ben'), (3, 'Cho');
INSERT INTO orders VALUES ('book', 1), ('pen', 1), ('lamp', 3), ('mug', 4);

Every join below has the same condition, ON o.user_id = u.id. Only the join type changes, and with it the rule for rows that match nothing.

02 Inner join: only the pairs that match

SQL
SELECT u.name, o.item
FROM users u
JOIN orders o ON o.user_id = u.id;

The plainest way to picture it: take each user in turn, compare them with every order, and output one row for each pair where the condition is true. JOIN on its own means INNER JOIN.

Inner join: try every pair, keep the matches
Step 1 of 13
users (id name)
1 Ana
2 Ben
3 Cho
orders (item → user_id)
book → 1
pen → 1
lamp → 3
mug → 4
inner join result
Empty
  • this user
  • ids match
  • ids differ
  • new result row
  • not reached yet

Nothing compared yet. The result starts empty.

0 of 12 comparisons

The rule is: a row comes out for every matching pair, and only for those. That is why Ana appears twice and Ben and the mug not at all. A join can return more rows than either table when one row matches many.

03 Left join: keep every row on the left

SQL
SELECT u.name, o.item
FROM users u
LEFT JOIN orders o ON o.user_id = u.id;
Left join: every user stays
Step 1 of 4
users (id name)
1 Ana
2 Ben
3 Cho
orders (item → user_id)
book → 1
pen → 1
lamp → 3
mug → 4
left join result
Empty
  • this user
  • ids match
  • new result row
  • not reached yet

Same tables, now users LEFT JOIN orders. Users is the left table: each of its rows must come out at least once.

The rule: the matching pairs, plus each left row that matched nothing, once, padded with `NULL`. Use it for “every user and their orders, if any”. To find the users with no orders at all, add WHERE o.user_id IS NULL: only the padded rows survive. A RIGHT JOIN is the same with the sides swapped; most people just swap the tables and write a left join.

04 Full join: keep unmatched rows on both sides

SQL
SELECT u.name, o.item
FROM users u
FULL JOIN orders o ON o.user_id = u.id;
Full join: nobody is left out
Step 1 of 5
users (id name)
1 Ana
2 Ben
3 Cho
orders (item → user_id)
book → 1
pen → 1
lamp → 3
mug → 4
full join result
Empty
  • this user
  • ids match
  • new result row
  • not reached yet

users FULL JOIN orders keeps unmatched rows from both sides. To do that it must remember which orders were matched; the tick marks them.

Full joins are handy for comparing two lists, such as yesterday’s export and today’s: the NULL side tells you which rows are only in one of them. Postgres, SQL Server and Oracle support FULL JOIN; MySQL does not, so there you combine a left join and a right join with UNION.

05 Same tables, three answers

Inner join3 rowsMatching pairs only. Ben and the mug vanish.
Left join4 rowsMatching pairs, plus Ben with NULL for the order.
Full join5 rowsMatching pairs, plus Ben, plus the mug with NULL for the user.

With no condition at all, CROSS JOIN outputs every pair: 3 × 4 = 12 rows. Every other join is that list of pairs, filtered by ON, with the unmatched rows added back according to the join type. The order the rows come out in is not guaranteed; add ORDER BY when it matters.

06 How the database really finds the pairs

Trying every pair is the meaning of a join, not always how it is computed. For big tables, the planner picks one of three methods. All three give the same rows; they differ in work.

Nested LoopEach left row looks up matchesWhat the trace drew. Fast when the left side is small and the right side has an index on the join column.
Hash JoinOne pass over each tableBuilds a hash table from the smaller side, keyed on the join column, then probes it once per row of the other. Common for big equality joins.
Merge JoinTwo sorted lists, walked togetherBoth sides sorted by the key, then read in step like a zip. Good when indexes already give sorted order.

Run EXPLAIN in front of the inner join and Postgres shows the method it chose, for example Hash Join with Hash Cond: (o.user_id = u.id).

07 When it bites

The most common join bug: a WHERE condition on the right table quietly turns a left join back into an inner join. WHERE runs after the join, and the padded rows have NULL there, which never equals anything.

Loses Ben and Cho
SELECT u.name, o.item
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.item = 'book';
-- Ana | book
Keeps every user
SELECT u.name, o.item
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
AND o.item = 'book';
-- Ana | book, Ben | NULL, Cho | NULL
SELECT u.name, count(*) ... LEFT JOIN ... GROUP BY u.nameCounting the padded rowBen’s NULL row is still a row, so count(*) says 1. Use count(o.item), which skips NULLs, and Ben gets 0.
ON o.user_id = u.id -- user_id IS NULLNULL keys never matchNULL = NULL is not true in SQL, so an order with no user_id never joins to anything, not even another NULL.
Two one-to-many joins multiplyJoin users to orders and to addresses in one query and each user’s rows become orders × addresses. Sums over orders then count each order once per address. Aggregate each side in a subquery first.

08 Check yourself

Question

Ana has 2 orders, Ben 0, Cho 1. How many rows does users LEFT JOIN orders return?

Question

You add WHERE o.item = 'pen' to that left join. Which users remain?

Question

An inner join between a 1,000-row table and a 10-row table returns 5,000 rows. Is that possible?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?