SELF JOIN & CROSS JOIN in SQL
Join a table to itself; know the cartesian explosion
SELF JOIN joins a table to itself with aliases — hierarchies (employee/manager), pairs, consecutive rows. CROSS JOIN produces the full cartesian product (every combination) — usually a forgotten-ON bug, deliberately for grids and test matrices. Non-equi joins match ranges instead of equality (salary bands, effective dates).
SELF needs two aliases
Same table left and right (e vs m). Alias discipline is readability.
Hierarchies via SELF
employee.manager_id → manager.id resolves names without a second table.
CROSS multiplies
No ON — every left × every right. 6 × 3 = 18 rows here.
Missing ON is a CROSS
Forgotten join condition silently becomes cartesian. Row-count check catches it.
1-- manager names via self join:2SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id LIMIT 2;
| name | manager |
|---|---|
| Alice | null |
| Bob | null |
Each employee row looks itself up as a manager row. With no manager_id populated the manager side is NULL — the LEFT preserves the employee. CROSS JOIN with departments would instead multiply every employee by every department.
Manager names via SELF
One table acts as two roles.
1SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id LIMIT 2;
| name | manager |
|---|---|
| Alice | null |
| Bob | null |
Deliberate CROSS grid
Every combination — test matrices, size/color grids.
1SELECT e.name, d.dept_id FROM employees e CROSS JOIN departments d LIMIT 3;
| name | dept_id |
|---|---|
| Alice | Engineering |
| Alice | Sales |
| Alice | Marketing |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.