Recursive CTE for an Org Chart
Walk a self-referencing employee table with a recursive CTE to list each person and their management depth from the top.
Code
WITH RECURSIVE org_chart AS (
SELECT
id,
name,
manager_id,
1 AS depth,
name AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT
e.id,
e.name,
e.manager_id,
oc.depth + 1,
oc.path || ' > ' || e.name
FROM employees e
JOIN org_chart oc ON e.manager_id = oc.id
)
SELECT id, name, depth, path
FROM org_chart
ORDER BY path;Inside the snippet
What runs is SELECT, with employees and org_chart as the object involved.
In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; a UNION stitching together the result sets of separate queries.
Putting it to use
The employees table is the working surface here.
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
- What are the relations in play here?
- The references are `employees`, `org_chart`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.