SQL Joins
Inner, left, right, full outer, cross and self joins with visual examples; joining on multiple tables; semi- and anti-joins with EXISTS; and common join mistakes.
Normalised data is spread across tables; joins put it back together. A join combines rows from two tables where a condition (usually key = foreign key) holds.
Example data:
| id | name | dept_id |
|---|---|---|
| 1 | Ada | 10 |
| 2 | Alan | 20 |
| 3 | Grace | 10 |
| 4 | Linus | NULL |
| id | name |
|---|---|
| 10 | Engineering |
| 20 | Research |
| 30 | Sales |
Join types
| Join | Returns |
|---|---|
INNER JOIN | Only rows with a match on both sides |
LEFT [OUTER] JOIN | All left rows; right columns NULL where there's no match |
RIGHT [OUTER] JOIN | All right rows; left columns NULL where there's no match |
FULL [OUTER] JOIN | All rows from both sides, NULLs where unmatched |
CROSS JOIN | Every combination (Cartesian product): m × n rows |
INNER JOIN
SELECT e.name, d.name AS dept
FROM employees e
JOIN departments d ON d.id = e.dept_id;| name | dept |
|---|---|
| Ada | Engineering |
| Alan | Research |
| Grace | Engineering |
Linus (no department) and Sales (no employees) disappear.
LEFT JOIN
SELECT e.name, d.name AS dept
FROM employees e
LEFT JOIN departments d ON d.id = e.dept_id;| name | dept |
|---|---|
| Ada | Engineering |
| Alan | Research |
| Grace | Engineering |
| Linus | NULL |
FULL OUTER JOIN
Everything from both sides: the four employees plus a row (NULL, Sales). (MySQL lacks FULL JOIN; emulate it with a LEFT JOIN UNION a RIGHT JOIN.)
Anti-join: rows without a match
"Departments with no employees":
-- LEFT JOIN + IS NULL
SELECT d.name
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.id
WHERE e.id IS NULL;
-- NOT EXISTS (clear and NULL-safe; usually the same plan)
SELECT d.name
FROM departments d
WHERE NOT EXISTS (SELECT 1 FROM employees e WHERE e.dept_id = d.id);Both return Sales.
Semi-join: rows with at least one match
"Departments that have employees" — without duplicating departments once per employee:
SELECT d.name
FROM departments d
WHERE EXISTS (SELECT 1 FROM employees e WHERE e.dept_id = d.id);Self join
A table joined to itself, e.g. employees and their managers:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;For arbitrary-depth hierarchies (an org chart, a comment thread), use a recursive CTE (Advanced SQL).
Joining many tables
SELECT c.name, o.id AS order_id, p.title, oi.quantity
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.created_at >= now() - interval '30 days';Common mistakes
- Fan-out (row multiplication) — joining orders to items and to payments multiplies rows: 3 items × 2 payments = 6 rows per order, and
SUM(amount)double-counts. Aggregate each child table in a subquery first, then join. - Missing join condition — an accidental cross join. 10,000 × 10,000 = 100 million rows.
- Joining on non-indexed columns — the foreign key columns (
orders.customer_id) usually need an index; databases don't always create one automatically (PostgreSQL doesn't). - Ambiguous columns — always alias tables and qualify columns.
How databases execute joins
| Algorithm | How | Good when |
|---|---|---|
| Nested loop | For each outer row, look up matches (ideally via an index) | Small outer side, indexed inner side |
| Hash join | Build a hash table on the smaller input, probe with the larger | Large unsorted inputs, equality joins |
| Merge join | Walk two inputs sorted on the join key | Inputs already sorted (indexes), range joins |
The optimiser chooses based on table statistics; EXPLAIN shows which it picked (Query processing).
- INNER keeps matches only; LEFT/RIGHT keep all of one side; FULL keeps both; CROSS is every pair.
- Anti-join: LEFT JOIN … IS NULL or NOT EXISTS. Semi-join: EXISTS.
- Self joins handle parent/child relationships in one table.
- Conditions on the optional side of an outer join belong in ON, not WHERE.
- Watch for fan-out when joining several one-to-many tables; aggregate first.
QFind customers who have never placed an order.easy
SELECT c.* FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id); — or a LEFT JOIN orders with WHERE o.id IS NULL.
QHow many rows does a LEFT JOIN return?medium
At least as many as the left table: each left row appears once if it has no match, or once per matching right row. So it can return more rows than the left table when the relationship is one-to-many.