Overview

A join combines rows from two tables based on a predicate. Choosing the right join type is mostly about which rows you want to keep when there is no match.

Core concepts

JoinKeeps
INNER JOINOnly matching pairs
LEFT [OUTER] JOINAll left rows; right columns are NULL when no match
RIGHT [OUTER] JOINMirror of left (rarely needed; swap the tables instead)
FULL [OUTER] JOINUnmatched rows from both sides
CROSS JOINEvery combination (Cartesian product)
SEMI / ANTILeft rows that have / do not have a match; written with EXISTS / NOT EXISTS
flowchart LR
  A[orders] -->|customer_id = id| B[customers]
  B --> C[result rows]

Worked example

Data: five customers, seven orders (Dan and Eve have none). Verified on PostgreSQL 17.

-- how many orders per customer, including customers with none
SELECT c.name, count(o.id) AS n
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
ORDER BY c.name;

Result: Ana 3, Bao 2, Chi 2, Dan 0, Eve 0. Using count(o.id) instead of count(*) matters: count(*) would report 1 for Dan and Eve because the outer join still produces one row for them.

Anti-join (customers with no orders):

SELECT c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

returns Dan and Eve.

How it works (internals)

Engines implement joins with three main algorithms; the optimizer picks one using row estimates (query-planning):

  • Nested loop: for each outer row, probe the inner side (best with an index on the join column and a small outer input).
  • Hash join: build a hash table on the smaller input, probe with the other (good for large unsorted inputs, equality only).
  • Merge join: both inputs sorted on the join key, merged in one pass (good when sorted by an index).

Pitfalls and production notes

  • Filter placement with outer joins. LEFT JOIN o ... WHERE o.status = 'paid' turns the outer join into an inner join, because NULL = 'paid' is not true. Put the condition in the ON clause to keep unmatched left rows.
  • Row multiplication. Joining on a non-unique key duplicates rows; a later SUM then double counts. Aggregate before joining, or join to a deduplicated set.
  • NOT IN with a nullable subquery returns nothing if any value is NULL (relational-model). Use NOT EXISTS.
  • Index the join columns on the many side (indexing-theory).

Practice questions

  1. Rewrite the anti-join with LEFT JOIN ... WHERE o.id IS NULL. When is it slower or equal?
  2. Why can a join between two million-row tables be fast with a nested loop?
  3. A report doubles revenue after adding a join to order_items. Why?

References

sql-aggregation · sql-window-functions · query-planning · relational-model