SQL Joins
A join combines rows from two tables according to a condition. Every join question reduces to three things: which rows are kept, what happens to rows that do not match, and where the filter goes.
The 60-second answer
Section titled “The 60-second answer”“An inner join returns only pairs satisfying the ON condition. A left join keeps every row from the left table and pads the right side with NULL; a right join is the mirror; a full join keeps unmatched rows from both sides. A cross join is every combination and is usually a mistake. ON decides what counts as a match, WHERE filters the joined result afterwards — which is why putting right_table.col = 1 in WHERE silently turns a left join into an inner join. Self joins use an alias to relate a table to itself, and anti-joins (LEFT JOIN ... WHERE right.id IS NULL, or NOT EXISTS) find rows with no match.”
Schema
Section titled “Schema”The five joins
Section titled “The five joins”-- Inner: books that have reviews, one row per reviewSELECT b.title, r.ratingFROM books bJOIN reviews r ON r.book_id = b.id;
-- Left: every book, with reviews where they existSELECT b.title, r.ratingFROM books bLEFT JOIN reviews r ON r.book_id = b.id;
-- Right: mirror image; prefer rewriting as a left join for readabilitySELECT b.title, r.ratingFROM reviews rRIGHT JOIN books b ON r.book_id = b.id;
-- Full: unmatched rows from both sidesSELECT b.title, r.ratingFROM books bFULL JOIN reviews r ON r.book_id = b.id;
-- Cross: every book paired with every author (n × m rows)SELECT b.title, a.name FROM books b CROSS JOIN authors a;| Join | Result size |
|---|---|
| Inner | One row per matching pair |
| Left | Matching pairs + one row per unmatched left row |
| Full | Matching pairs + unmatched left + unmatched right |
| Cross | count(left) × count(right) |
A left join does not return one row per left row when the right side has duplicates — it returns one row per combination. “Each book with its review count” is a GROUP BY or a lateral subquery; a plain left join then COUNT(*) over-counts a book with 3 reviews.
ON versus WHERE
Section titled “ON versus WHERE”-- Wrong: this is an inner join with extra stepsSELECT b.title, r.ratingFROM books bLEFT JOIN reviews r ON r.book_id = b.idWHERE r.rating >= 4;
-- Right: filter inside the join conditionSELECT b.title, r.ratingFROM books bLEFT JOIN reviews r ON r.book_id = b.id AND r.rating >= 4;In the first query, books with no 4+ review have r.rating = NULL, and NULL >= 4 is NULL, not true, so the row is filtered out. Rule: conditions on the optional table go in ON; conditions on the required table can go in WHERE.
Anti-joins and semi-joins
Section titled “Anti-joins and semi-joins”-- Authors with no booksSELECT a.nameFROM authors aLEFT JOIN books b ON b.author_id = a.idWHERE b.id IS NULL;
-- NOT EXISTS: usually clearest, and NULL-safeSELECT a.nameFROM authors aWHERE NOT EXISTS (SELECT 1 FROM books b WHERE b.author_id = a.id);
-- NOT IN: dangerous with NULLsSELECT a.name FROM authors aWHERE a.id NOT IN (SELECT author_id FROM books);NOT IN returns no rows if the subquery yields a single NULL, because x NOT IN (1, NULL) evaluates to NULL, never true. author_id is NOT NULL above so it happens to work; make the column nullable and the query silently returns nothing. Prefer NOT EXISTS.
The semi-join is the inverse: rows that do have a match, without duplicating them.
Self joins
Section titled “Self joins”The alias is mandatory: referencing a table twice makes the unaliased name ambiguous. Self joins are the answer to “compare rows within a table”, alongside window functions.
Join versus subquery
Section titled “Join versus subquery”Both are correct; PostgreSQL often rewrites one into the other. Choose by intent: EXISTS for existence checks (no duplicates, no GROUP BY), JOIN when you need columns from both tables, a scalar subquery for one aggregate per outer row. LATERAL when the subquery needs the outer row and returns several columns:
That “latest row per parent” pattern is the most useful lateral join in practice.
Join algorithms
Section titled “Join algorithms”| Algorithm | Cost shape | Chosen when |
|---|---|---|
| Nested loop | Outer rows × index probes | Small outer side, indexed inner side |
| Hash join | Build a hash on the smaller side | Large unsorted inputs, equality join |
| Merge join | Sort both sides, then zip | Both inputs already sorted |
A nested loop over a million outer rows with an unindexed inner table is the classic slow query: it becomes a million sequential scans. That is exactly what EXPLAIN shows as “Nested Loop … Seq Scan”.
Follow-up questions
Section titled “Follow-up questions”- Why does a
WHEREcondition on the right table of a left join behave like an inner join? - When does a left join return more rows than the left table has?
- Why can
NOT INreturn an empty result, and what do you use instead? - What is the difference between
EXISTSand a join for existence checks? - Which join algorithm would you expect for a small table joined to an indexed large table?
Common traps
Section titled “Common traps”WHEREversusONon an outer join. The most common join bug.COUNT(*)after a left join. Counts the padded row as 1; useCOUNT(r.id).NOT INwith a nullable column. Silently returns nothing.- Assuming a left join preserves one row per left row. Duplicates on the right multiply.
- Cross join by accident. A missing
ONclause is a cartesian product, not an error. SELECT *across a join. Collidingidcolumns and unnecessary data over the wire.