// SQL snippet

Walk an org chart

Seed the manager, then join children onto the frontier until none remain.

Main statement
PostgreSQL
다음도 지원
SQL Server Oracle

The task

You want everyone reporting, directly or not, to employee 42, with how deep they sit below them.

The snippet

Written for PostgreSQL. Versions for SQL Server and Oracle are under Variations.

PostgreSQL
WITH RECURSIVE subordinates AS (
  SELECT id, name, manager_id, 0 AS depth
  FROM employees
  WHERE id = 42
  UNION ALL
  SELECT e.id, e.name, e.manager_id, s.depth + 1
  FROM employees e
  JOIN subordinates s ON e.manager_id = s.id
)
SELECT id, name, depth
FROM subordinates
ORDER BY depth, name;

작동 방식

The anchor is the manager themself at depth 0; each recursive round joins the current frontier's direct reports one level deeper. Depth makes the output sortable by level and gives you something to cap if the data contains a loop. The statement runs unchanged on PostgreSQL, MySQL 8 and SQLite. SQL Server and Oracle drop the RECURSIVE keyword; Oracle also requires the column list after the CTE name, which SQL Server accepts too. SQL Server stops any recursive CTE after 100 levels by default (OPTION (MAXRECURSION n) changes that).

Variations

Walk upward: the chain of managers

WITH RECURSIVE managers AS (
  SELECT id, name, manager_id
  FROM employees
  WHERE id = 42
  UNION ALL
  SELECT e.id, e.name, e.manager_id
  FROM employees e
  JOIN managers m ON e.id = m.manager_id
)
SELECT id, name, manager_id
FROM managers
ORDER BY id;

SQL Server and Oracle: no RECURSIVE, explicit column list

SQL Server Oracle
WITH subordinates (id, name, manager_id, depth) AS (
  SELECT id, name, manager_id, 0
  FROM employees
  WHERE id = 42
  UNION ALL
  SELECT e.id, e.name, e.manager_id, s.depth + 1
  FROM employees e
  JOIN subordinates s ON e.manager_id = s.id
)
SELECT id, name, depth
FROM subordinates
ORDER BY depth, name;

Questions that come up

What if the data has a manager loop?

A loop such as A managing B managing A makes the recursion grow without end (SQL Server aborts at its 100-level default; PostgreSQL and SQLite keep going; MySQL stops at cte_max_recursion_depth, 1000 by default). Add a depth cap (WHERE s.depth < 20) or a visited guard as in the cycle-guard recipe, and fix the data.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.