Self Join Hierarchy Employee Manager
Query an employee manager hierarchy using a self join with multiple levels to flatten the organizational structure.
Code
SELECT
e.employee_id,
e.employee_name,
m1.employee_name AS manager_name,
m2.employee_name AS grandmanager_name
FROM employees e
LEFT JOIN employees m1 ON e.manager_id = m1.employee_id
LEFT JOIN employees m2 ON m1.manager_id = m2.employee_id
ORDER BY e.employee_id;Inside the snippet
At its core this is a single SELECT statement against employees.
Mechanically, the statements are built from: 2 JOINs combining rows across tables; an ORDER BY that fixes the output order.
What to watch for
- 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.
Using it
The employees table is the working surface here.
Key statements
SELECT
e.employee_id,
e.employee_name,
m1.employee_name AS manager_name,
m2.employee_name AS grandmanager_name
FROM employees e
LEFT JOIN employees m1 ON e.manager_id = m1.employee_id
LEFT JOIN employees m2 ON m1.manager_id = m2.employee_id
ORDER BY e.employee_id;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does this file reference?
- `employees`, combined through 2 joins.
Report a problem with this exampleOpens a pre-filled issue on GitHub.