Skip to content

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.

“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.”

-- Inner: books that have reviews, one row per review
SELECT b.title, r.rating
FROM books b
JOIN reviews r ON r.book_id = b.id;
-- Left: every book, with reviews where they exist
SELECT b.title, r.rating
FROM books b
LEFT JOIN reviews r ON r.book_id = b.id;
-- Right: mirror image; prefer rewriting as a left join for readability
SELECT b.title, r.rating
FROM reviews r
RIGHT JOIN books b ON r.book_id = b.id;
-- Full: unmatched rows from both sides
SELECT b.title, r.rating
FROM books b
FULL 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.

-- Wrong: this is an inner join with extra steps
SELECT b.title, r.rating
FROM books b
LEFT JOIN reviews r ON r.book_id = b.id
WHERE r.rating >= 4;
-- Right: filter inside the join condition
SELECT b.title, r.rating
FROM books b
LEFT 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.

-- Authors with no books
SELECT a.name
FROM authors a
LEFT JOIN books b ON b.author_id = a.id
WHERE b.id IS NULL;
-- NOT EXISTS: usually clearest, and NULL-safe
SELECT a.name
FROM authors a
WHERE NOT EXISTS (SELECT 1 FROM books b WHERE b.author_id = a.id);
-- NOT IN: dangerous with NULLs
SELECT a.name FROM authors a
WHERE 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.

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.

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.

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”.

  1. Why does a WHERE condition on the right table of a left join behave like an inner join?
  2. When does a left join return more rows than the left table has?
  3. Why can NOT IN return an empty result, and what do you use instead?
  4. What is the difference between EXISTS and a join for existence checks?
  5. Which join algorithm would you expect for a small table joined to an indexed large table?
  • WHERE versus ON on an outer join. The most common join bug.
  • COUNT(*) after a left join. Counts the padded row as 1; use COUNT(r.id).
  • NOT IN with 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 ON clause is a cartesian product, not an error.
  • SELECT * across a join. Colliding id columns and unnecessary data over the wire.