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.

Beginner 3 min readLesson 3 of 14 Interview Q&A

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:

employees
idnamedept_id
1Ada10
2Alan20
3Grace10
4LinusNULL
departments
idname
10Engineering
20Research
30Sales

Join types

JoinReturns
INNER JOINOnly rows with a match on both sides
LEFT [OUTER] JOINAll left rows; right columns NULL where there's no match
RIGHT [OUTER] JOINAll right rows; left columns NULL where there's no match
FULL [OUTER] JOINAll rows from both sides, NULLs where unmatched
CROSS JOINEvery combination (Cartesian product): m × n rows

INNER JOIN

SQL
SELECT e.name, d.name AS dept
FROM employees e
JOIN departments d ON d.id = e.dept_id;
namedept
AdaEngineering
AlanResearch
GraceEngineering

Linus (no department) and Sales (no employees) disappear.

LEFT JOIN

SQL
SELECT e.name, d.name AS dept
FROM employees e
LEFT JOIN departments d ON d.id = e.dept_id;
namedept
AdaEngineering
AlanResearch
GraceEngineering
LinusNULL

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":

SQL
-- 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:

SQL
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:

SQL
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

SQL
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

AlgorithmHowGood when
Nested loopFor each outer row, look up matches (ideally via an index)Small outer side, indexed inner side
Hash joinBuild a hash table on the smaller input, probe with the largerLarge unsorted inputs, equality joins
Merge joinWalk two inputs sorted on the join keyInputs already sorted (indexes), range joins

The optimiser chooses based on table statistics; EXPLAIN shows which it picked (Query processing).

Key takeaways
  • 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.
Interview questions
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.