Learn SQL Lesson
SELF JOIN for Hierarchies
A self join joins a table to itself. This is common when rows relate to other rows in the same table, such as employees and managers.
SELECT e.name AS employee_name, m.name AS manager_name
FROM employees AS e
LEFT JOIN employees AS m
ON e.manager_id = m.id
The `employees` table appears twice with different aliases. One copy represents the employee, and the other represents the manager.
This pattern is useful for org charts, parent-child relationships, and tree-like data.
Practice challenge
List every employee together with their manager. Return employee_name and manager_name, ordered by employee_name. Include Alice with a NULL manager_name.