Hierarchy Traversal
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.idThe classic self-join. A table references itself through a foreign key (like manager_id pointing to id in the same employees table). This pattern handles org charts, category trees, and any parent-child relationship stored in a single table.
Common use cases
- Find each employee and their manager name
- List all direct reports for a given manager
- Build multi-level org charts (chain multiple self-joins)
- Find root nodes (WHERE manager_id IS NULL)
Interview tip: Always use LEFT JOIN for hierarchies, not INNER JOIN. INNER JOIN drops the CEO (or any root node) because their manager_id is NULL and has no match.