Home › Learn › SQL › Joins

Self join

Lesson 19 of 26. Join a table to itself for hierarchies.

Employees have a manager_id pointing at another employee. To show each person with their manager's name, join employees to itself with two aliases: one copy plays the employee, the other the manager. FROM employees e JOIN employees m ON m.id = e.manager_id.

The top of the hierarchy has a NULL manager_id and disappears from an inner self join; use a LEFT JOIN to keep them.

SELECT e.name, m.name AS manager
FROM employees e LEFT JOIN employees m ON m.id = e.manager_id;

Your task

Show each employee's name and their manager's name, only for employees who have a manager.

Hint 1

JOIN employees m ON m.id = e.manager_id

Show the solution
SELECT e.name, m.name
FROM employees e JOIN employees m ON m.id = e.manager_id;

    Runs SQLite compiled to WebAssembly in this tab; the database is rebuilt before every run.