skipnothing/SQL

Self & Cross Joins

The employees table carries a manager_id column that points right back at its own id. Stand the table up beside a second copy of itself, and every worker can meet their boss on a single row.

  • ▸Alias one table into two copies; an ordinary inner join then pairs each employee with their manager.
  • ▸Paired with itself on manager_id, a table matches each managed row to itself until a.id < b.id trims the doubles.
  • ▸Drop the WHERE from FROM users, orders and you get the same explosion as every-row-times-every-row, with no warning.
BUILDS ON
01

Join a Table to Itself

Here is the employees table: Ada with manager_id NULL because she runs the place, Brent and Cleo both reporting to Ada with manager_id 1, and Dee reporting to Brent with manager_id 2. The boss's name is sitting in the same table as the worker, a row or two above, but a single scan of one row can't reach another row to read it.

So treat the one table as two. Name a first copy e for the employee side and a second copy m for the manager side, then pair them: SELECT e.name AS employee, m.name AS manager FROM employees e JOIN employees m ON e.manager_id = m.id. Nothing here is a new operator. It is the same inner join pairing rows on a condition, except both sides draw from employees. The pairing arrow runs from e.manager_id to m.id: Brent's manager_id is 1, Ada's id is 1, so (Brent, Ada) is a kept pair.

The aliases are not optional decoration. Write name without a prefix and the engine can't tell which copy you mean, the query is ambiguous and rejected. Ada herself drops out of the result: her manager_id is NULL, NULL equals nothing, so the inner join finds no manager row to pair her with.

ONE TABLE, TWO ROLES

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL