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
| Join | Keeps |
|---|---|
INNER JOIN | Only matching pairs |
LEFT [OUTER] JOIN | All left rows; right columns are NULL when no match |
RIGHT [OUTER] JOIN | Mirror of left (rarely needed; swap the tables instead) |
FULL [OUTER] JOIN | Unmatched rows from both sides |
CROSS JOIN | Every combination (Cartesian product) |
SEMI / ANTI | Left 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, becauseNULL = 'paid'is not true. Put the condition in theONclause to keep unmatched left rows. - Row multiplication. Joining on a non-unique key duplicates rows; a later
SUMthen double counts. Aggregate before joining, or join to a deduplicated set. NOT INwith a nullable subquery returns nothing if any value isNULL(relational-model). UseNOT EXISTS.- Index the join columns on the many side (indexing-theory).
Practice questions
- Rewrite the anti-join with
LEFT JOIN ... WHERE o.id IS NULL. When is it slower or equal? - Why can a join between two million-row tables be fast with a nested loop?
- A report doubles revenue after adding a join to
order_items. Why?
References
- PostgreSQL manual, Table Expressions / Joined Tables: https://www.postgresql.org/docs/current/queries-table-expressions.html
Related
sql-aggregation · sql-window-functions · query-planning · relational-model