Course outline · 0% complete

0/29 lessons0%

Course overview →

Self Joins: A Table Meets Itself

lesson 6-3 · ~10 min · 17/29

When the foreign key points home

This shape is everywhere once you look: a comment stores the id of its parent comment, a category stores its parent category, a user stores who referred them. Whenever a row relates to another row of the same kind, the foreign key points at its own table. The classic example is an employees table that stores who manages whom with a manager_id column pointing at another row in the same table:

idnamemanager_id
1AnaNULL
2Ben1
3Cara1
4Dan2

Ana is the boss (no manager). To print each worker next to their manager's name, you join the table to itself. That requires giving the table two temporary names, called aliases, with AS:

SELECT worker.name, boss.name
FROM employees AS worker
JOIN employees AS boss ON boss.id = worker.manager_id
ORDER BY worker.id;

Mentally there are now two copies of employees: one playing the worker role, one playing the boss role. The ON rule connects a worker's manager_id to a boss's id.

Code exercise · sql

Run it. Three rows, one per employee who has a manager. Ana is missing: her manager_id is NULL, and an INNER JOIN drops the unmatched.

Quiz

Why does the self join need the aliases worker and boss?

Code exercise · sql

Your turn. Include Ana in the listing: change the join so every employee prints, with an empty manager spot for anyone who has no manager. Lesson 6-1 taught the join that keeps unmatched rows.

Code exercise · sql

Drill. Count how many direct reports each manager has, alphabetically by manager name. Combine the self join with GROUP BY from lesson 5-3.