Sub topic 11
Joining a Table to Itself
Assume you know basic SELECT syntax, primary and foreign keys, table aliases, and the ON clause. A self join uses one table twice in the same query. Each use gets a different alias, so each alias can play a different role.
The employee-manager example
Suppose an employees table stores each employee's manager in manager_id:
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
manager_id INTEGER REFERENCES employees (id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ada', NULL),
(2, 'Ben', 1),
(3, 'Chloe', 1),
(4, 'Diego', 2);
SELECT
e.name AS employee,
m.name AS manager
FROM employees AS e
INNER JOIN employees AS m
ON m.id = e.manager_id
ORDER BY e.id;The table appears twice:
employees AS erepresents the employee.employees AS mrepresents the employee's manager.
The join matches the manager's id with the employee's manager_id. The result is:
| employee | manager |
|---|---|
| Ben | Ada |
| Chloe | Ada |
| Diego | Ben |
Ada has a NULL manager ID. Because this is an INNER JOIN, Ada has no matching manager row and is excluded.
Reading the relationship direction
Foreign keys often point from a child row to a parent row. Here, e.manager_id points to m.id.
The direction in the query matters. This condition finds each employee's manager:
ON m.id = e.manager_idReversing the roles can answer a different question, such as finding each manager's direct reports:
SELECT
m.name AS manager,
e.name AS employee
FROM employees AS m
INNER JOIN employees AS e
ON e.manager_id = m.id
ORDER BY m.id, e.id;Here, m is the manager role and e is the employee role.
Common mistakes
Use two distinct aliases. A query such as FROM employees AS e INNER JOIN employees AS e gives both table instances the same name and cannot identify the roles.
Qualify every repeated column with its alias. Both table instances have an id and a name, so writing SELECT name is ambiguous. Write e.name or m.name.
Remember that one manager can match many employee rows. Ada appears once for Ben and once for Chloe because the join returns one result row for each matching pair.
If you need employees who do not have a manager, use a LEFT JOIN instead:
SELECT e.name AS employee, m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m
ON m.id = e.manager_id;Exercise
Which employees appear in the inner-join query if a new employee named Elena has manager_id = 99, but no employee has id 99?
Show answer
Elena is excluded because her manager_id has no matching row in the second employees instance.