Cheatsheet Pages / SQL Cheatsheet

How to join a table to itself in SQL — self join for org charts

The hierarchy lives in one table: each employee row points at their manager in the same table.

Every example runs against the cheatsheet's sample tables — departments(id, name), employees(id, name, dept_id, salary, manager_id, hired_on) and orders(id, emp_id, amount, ordered_on) — and was executed and verified against SQLite, so you can paste it in and get the same result.

SELECT e.name AS employee, m.name AS manager
FROM employees e LEFT JOIN employees m ON e.manager_id = m.id;
-- Bob→Alice, Carol→Alice, Eve→David; people without a manager get NULL
-- Org charts, threaded comments, any hierarchy stored in one table works this way
SQL Cheatsheet one-page card — queries that actually work
The full one-page card — SQL Cheatsheet. Get the complete cheatsheet on GitHub