Part 05 / Topic 5 of 9
Self joins
Nothing says the two tables must be different. employees points at itself — manager_id references another employee — so "each employee with their manager" joins the table to the table:
SELECT e.name AS employee, e.title, m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY e.employee_id;
employee | title | manager
----------+------------+---------
Nina | CEO |
Omar | CTO | Nina
Priya | Sales Head | Nina
Arjun | Engineer | Omar
Lena | Engineer | Omar
Dev | Sales Rep | Priya
(6 rows)
The aliases do all the work: e is the table wearing its "employee" hat, m the same table wearing its "manager" hat. LEFT (not inner) keeps Nina, the CEO — her manager_id is NULL, and an inner join would silently drop the one person with no boss.
Same pattern, same table, different question: categories.parent_id points at categories — sub-categories and their parents. (Walking a whole tree of any depth needs a recursive CTE — a Stage 3 lesson.)
🧪 Quick quiz — answer from memory, then check.
- Why must the self join on employees be LEFT, not INNER?
- What distinguishes the two "copies" of the table in a self join?
Show the answers
- The CEO's manager_id is NULL — an inner join drops her; LEFT keeps her with a NULL manager.
- Only their aliases (
evsm) — each alias is an independent view of the same table.
Done here? The practice set for Part 5 — 8 exercises with solutions — is on the part page.