JuniorCodingSQL
Write a query that lists each employee with their manager's name
Try answering first
Model answer
The manager is just another row in the same table, so join the table to itself. A self join needs two different aliases, so the database knows which copy each column comes from.
SELECT e.name AS employee,
m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id
ORDER BY e.name;
Read it as two roles: e is the employee, m is the manager row that e.manager_id points to.
The LEFT JOIN matters. The CEO has manager_id = NULL, so there is no match. An INNER JOIN would drop that employee silently, while the LEFT JOIN keeps the row and shows NULL as the manager.
The same pattern answers related questions, for example employees who earn more than their manager:
SELECT e.name
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;
Self joins fit one level of hierarchy. For arbitrary depth, use a recursive CTE.
Key points
- Self join uses the same table twice with different aliases
- Join employee.manager_id to manager.id
- LEFT JOIN keeps employees with no manager
- Recursive CTE handles unlimited depth
Likely follow-ups
- How do you list managers who have no direct reports?
Common mistakes
- Using INNER JOIN and losing the top of the hierarchy
- Forgetting aliases and getting ambiguous column errors