Following a Hierarchy with Recursive WITH

Org charts, bills of materials, and category trees are stored with each row holding its parent's key (mgr_id is the manager's emp_id). Such a hierarchy is followed one level at a time with a recursive WITH. The anchor part picks the starting rows, and the recursive part joins the children (or parents) of the rows from the previous step.

Sample data

The sample schema has no hierarchy table, so the org chart below is used as a CTE org built with VALUES. All three DBs accept FROM (VALUES …) AS t (col, …).

CEO (1)
├─ CTO (2)
│  ├─ Dev Lead (4)
│  │  ├─ Dev A (6)
│  │  └─ Dev B (7)
│  └─ QA Lead (5)
└─ CFO (3)
   └─ Accountant (8)

Top down: depth and path

The anchor part is the row with no parent (mgr_id IS NULL). The recursive part finds the subordinates of the previous step's rows with e.mgr_id = r.emp_id, adds 1 to the depth, and appends the name to the path string.

PostgreSQL · Whole org chart with depth and path

WITH RECURSIVE org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', NULL), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2),
                        (5, 'QA Lead', 2), (6, 'Dev A', 4), (7, 'Dev B', 4), (8, 'Accountant', 3)
  ) AS t (emp_id, emp_nm, mgr_id)
),
r (emp_id, emp_nm, depth, path) AS (
  SELECT emp_id, emp_nm, 1, CAST(emp_nm AS VARCHAR(200))
  FROM org WHERE mgr_id IS NULL
  UNION ALL
  SELECT e.emp_id, e.emp_nm, r.depth + 1, CAST(r.path || ' > ' || e.emp_nm AS VARCHAR(200))
  FROM org e JOIN r ON e.mgr_id = r.emp_id
)
SELECT emp_id, emp_nm, depth, path FROM r ORDER BY path

Oracle · Whole org chart with depth and path

WITH org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', NULL), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2),
                        (5, 'QA Lead', 2), (6, 'Dev A', 4), (7, 'Dev B', 4), (8, 'Accountant', 3)
  ) AS t (emp_id, emp_nm, mgr_id)
),
r (emp_id, emp_nm, depth, path) AS (
  SELECT emp_id, emp_nm, 1, CAST(emp_nm AS VARCHAR(200))
  FROM org WHERE mgr_id IS NULL
  UNION ALL
  SELECT e.emp_id, e.emp_nm, r.depth + 1, CAST(r.path || ' > ' || e.emp_nm AS VARCHAR(200))
  FROM org e JOIN r ON e.mgr_id = r.emp_id
)
SELECT emp_id, emp_nm, depth, path FROM r ORDER BY path

SQL Server · Whole org chart with depth and path

WITH org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', NULL), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2),
                        (5, 'QA Lead', 2), (6, 'Dev A', 4), (7, 'Dev B', 4), (8, 'Accountant', 3)
  ) AS t (emp_id, emp_nm, mgr_id)
),
r (emp_id, emp_nm, depth, path) AS (
  SELECT emp_id, emp_nm, 1, CAST(emp_nm AS VARCHAR(200))
  FROM org WHERE mgr_id IS NULL
  UNION ALL
  SELECT e.emp_id, e.emp_nm, r.depth + 1, CAST(r.path + ' > ' + e.emp_nm AS VARCHAR(200))
  FROM org e JOIN r ON e.mgr_id = r.emp_id
)
SELECT emp_id, emp_nm, depth, path FROM r ORDER BY path

In PostgreSQL, RECURSIVE is written once, right after WITH. The first CTE in the list (org) does not have to be recursive.

The path column must have the same type in the anchor part and the recursive part. The string in the recursive part grows at each step, so both parts are CAST to the same length.

DBWithout CAST
SQL ServerRemoving both is an error: Types don't match between the anchor and the recursive part (Msg 240)
PostgreSQLCasting only the anchor part is an error: character varying(200) in non-recursive term but type character varying overall (42804). Removing both runs, because both are text
OracleIn this example, removing both still runs

To use the same rule in all three DBs, write CAST(… AS VARCHAR(n)) on both sides.

Bottom up: the chain of ancestors

To reverse the direction, flip only the join condition. The anchor part picks one person, and the recursive part finds the manager of the previous step's row with m.emp_id = up.mgr_id. When it reaches the top (mgr_id is NULL), there are no more rows to find, so it stops.

PostgreSQL · From Dev B (7) up to the CEO

WITH RECURSIVE org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', NULL), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2),
                        (5, 'QA Lead', 2), (6, 'Dev A', 4), (7, 'Dev B', 4), (8, 'Accountant', 3)
  ) AS t (emp_id, emp_nm, mgr_id)
),
up (emp_id, emp_nm, mgr_id, lvl) AS (
  SELECT emp_id, emp_nm, mgr_id, 0 FROM org WHERE emp_id = 7
  UNION ALL
  SELECT m.emp_id, m.emp_nm, m.mgr_id, up.lvl + 1
  FROM org m JOIN up ON m.emp_id = up.mgr_id
)
SELECT emp_id, emp_nm, lvl FROM up ORDER BY lvl

Oracle, SQL Server · From Dev B (7) up to the CEO

WITH org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', NULL), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2),
                        (5, 'QA Lead', 2), (6, 'Dev A', 4), (7, 'Dev B', 4), (8, 'Accountant', 3)
  ) AS t (emp_id, emp_nm, mgr_id)
),
up (emp_id, emp_nm, mgr_id, lvl) AS (
  SELECT emp_id, emp_nm, mgr_id, 0 FROM org WHERE emp_id = 7
  UNION ALL
  SELECT m.emp_id, m.emp_nm, m.mgr_id, up.lvl + 1
  FROM org m JOIN up ON m.emp_id = up.mgr_id
)
SELECT emp_id, emp_nm, lvl FROM up ORDER BY lvl

The result is 4 rows: Dev B, Dev Lead, CTO, CEO.

Depth-first ordering

The order in which a recursive WITH returns rows is undefined. To see it as a tree (each parent directly followed by its children), specify the order yourself.

  • Sort by path: the ORDER BY path above. A path starts with its parent's path, so children come right after their parent. Siblings follow the string order of their names. If you build the path from numeric ids, the comparison is a string comparison, so '/1/10/' comes before '/1/9/'.
  • SEARCH clause: standard syntax. PostgreSQL and Oracle support it; SQL Server does not. SEARCH DEPTH FIRST BY col SET ord_col orders siblings by the BY column and creates a column holding the depth-first order. BREADTH FIRST lists rows by depth.

PostgreSQL · SEARCH DEPTH FIRST

WITH RECURSIVE org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', NULL), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2),
                        (5, 'QA Lead', 2), (6, 'Dev A', 4), (7, 'Dev B', 4), (8, 'Accountant', 3)
  ) AS t (emp_id, emp_nm, mgr_id)
),
r (emp_id, emp_nm, depth) AS (
  SELECT emp_id, emp_nm, 1 FROM org WHERE mgr_id IS NULL
  UNION ALL
  SELECT e.emp_id, e.emp_nm, r.depth + 1 FROM org e JOIN r ON e.mgr_id = r.emp_id
) SEARCH DEPTH FIRST BY emp_nm SET ord
SELECT emp_id, emp_nm, depth, ord FROM r ORDER BY ord

Oracle · SEARCH DEPTH FIRST

WITH org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', NULL), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2),
                        (5, 'QA Lead', 2), (6, 'Dev A', 4), (7, 'Dev B', 4), (8, 'Accountant', 3)
  ) AS t (emp_id, emp_nm, mgr_id)
),
r (emp_id, emp_nm, depth) AS (
  SELECT emp_id, emp_nm, 1 FROM org WHERE mgr_id IS NULL
  UNION ALL
  SELECT e.emp_id, e.emp_nm, r.depth + 1 FROM org e JOIN r ON e.mgr_id = r.emp_id
) SEARCH DEPTH FIRST BY emp_nm SET ord
SELECT emp_id, emp_nm, depth, ord FROM r ORDER BY ord

The column created by SET is a value used for sorting. In Oracle it is a number starting at 1; in PostgreSQL it is an array of the emp_nm values passed through. The order is the same in both DBs.

Cycle detection

If the data is wrong and following parents leads back to the row itself, the recursion never ends. In the example below, the CEO's mgr_id is wrongly set to 6 (Dev A), so the data loops 1 → 2 → 4 → 6 → 1. There is no top-level row, so it starts at emp_id = 1.

Running it without guarding against the cycle gives the following.

DBCyclic data with no safeguard
OracleORA-32044: cycle detected while executing recursive WITH query
PostgreSQLDoes not notice the cycle. Running with WHERE r.depth < 8 in the recursive part returns the same rows again from the CEO (1), with only the depth changed
SQL ServerStops with an error at MAXRECURSION levels (default 100)

PostgreSQL and Oracle detect cycles with the standard CYCLE clause. CYCLE col SET flag_col changes the flag column of a row whose col value equals that of a row already passed through, and does not go further down from that row.

PostgreSQLOracle
SyntaxCYCLE emp_id SET is_cycle USING cyc_pathCYCLE emp_id SET is_cycle TO 'Y' DEFAULT 'N'
Flag valuesboolean if TO … DEFAULT … is omittedTO … DEFAULT … required (omitting it gives ORA-00946)
Path columnUSING required (array of values passed through)no USING

PostgreSQL · Cycle detection with the CYCLE clause

WITH RECURSIVE org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', 6), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2), (6, 'Dev A', 4)
  ) AS t (emp_id, emp_nm, mgr_id)
),
r (emp_id, emp_nm, depth) AS (
  SELECT emp_id, emp_nm, 1 FROM org WHERE emp_id = 1
  UNION ALL
  SELECT e.emp_id, e.emp_nm, r.depth + 1 FROM org e JOIN r ON e.mgr_id = r.emp_id
) CYCLE emp_id SET is_cycle TO 'Y' DEFAULT 'N' USING cyc_path
SELECT emp_id, emp_nm, depth, is_cycle, cyc_path FROM r

Oracle · Cycle detection with the CYCLE clause

WITH org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', 6), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2), (6, 'Dev A', 4)
  ) AS t (emp_id, emp_nm, mgr_id)
),
r (emp_id, emp_nm, depth) AS (
  SELECT emp_id, emp_nm, 1 FROM org WHERE emp_id = 1
  UNION ALL
  SELECT e.emp_id, e.emp_nm, r.depth + 1 FROM org e JOIN r ON e.mgr_id = r.emp_id
) CYCLE emp_id SET is_cycle TO 'Y' DEFAULT 'N'
SELECT emp_id, emp_nm, depth, is_cycle FROM r

Both DBs return 6 rows, and only the last row (the CEO at depth 5) has is_cycle = 'Y'.

SQL Server has no CYCLE clause. Carry the ids passed through as a path string such as '/1/2/4/'; if the next id is already in the path, flag it and stop at that row. Compare with the id wrapped in delimiters so that 1 does not falsely match inside /10/. Keep OPTION (MAXRECURSION n) as well, as a safeguard in case the logic is wrong.

SQL Server · Cycle detection with a path string

WITH org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', 6), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2), (6, 'Dev A', 4)
  ) AS t (emp_id, emp_nm, mgr_id)
),
r (emp_id, emp_nm, depth, id_path, is_cycle) AS (
  SELECT emp_id, emp_nm, 1, CAST('/' + CAST(emp_id AS VARCHAR(10)) + '/' AS VARCHAR(200)), 0
  FROM org WHERE emp_id = 1
  UNION ALL
  SELECT e.emp_id, e.emp_nm, r.depth + 1,
         CAST(r.id_path + CAST(e.emp_id AS VARCHAR(10)) + '/' AS VARCHAR(200)),
         CASE WHEN r.id_path LIKE '%/' + CAST(e.emp_id AS VARCHAR(10)) + '/%' THEN 1 ELSE 0 END
  FROM org e JOIN r ON e.mgr_id = r.emp_id
  WHERE r.is_cycle = 0
)
SELECT emp_id, emp_nm, depth, id_path, is_cycle FROM r
OPTION (MAXRECURSION 20)

The WHERE r.is_cycle = 0 in the recursive part keeps the query from going further down from a row flagged as a cycle. Switched to ||, this method gives the same result in PostgreSQL and Oracle as well.

Oracle: CONNECT BY

Oracle has a hierarchical query syntax that predates recursive WITH. START WITH is the anchor part, and CONNECT BY PRIOR parent_side = child_side is the join condition of the recursive part.

SyntaxMeaning
LEVELdepth (the starting row is 1)
SYS_CONNECT_BY_PATH(col, '/')path string from the starting row to the current row
CONNECT_BY_ROOT colvalue from the starting row the current row belongs to
CONNECT_BY_ISLEAF1 if the row has no children
ORDER SIBLINGS BY colsorts only among siblings, keeping the tree shape
CONNECT BY NOCYCLE, CONNECT_BY_ISCYCLEdoes not stop at a cycle, and flags with 1 the row whose child is an ancestor

Oracle · Tree per division, CTO and CFO

WITH org (emp_id, emp_nm, mgr_id) AS (
  SELECT * FROM (VALUES (1, 'CEO', NULL), (2, 'CTO', 1), (3, 'CFO', 1), (4, 'Dev Lead', 2),
                        (5, 'QA Lead', 2), (6, 'Dev A', 4), (7, 'Dev B', 4), (8, 'Accountant', 3)
  ) AS t (emp_id, emp_nm, mgr_id)
)
SELECT LEVEL AS lvl, emp_id,
       LPAD(' ', 2 * (LEVEL - 1)) || emp_nm AS tree,
       SYS_CONNECT_BY_PATH(emp_nm, '/')     AS path,
       CONNECT_BY_ROOT emp_nm               AS division,
       CONNECT_BY_ISLEAF                    AS is_leaf
FROM org
START WITH mgr_id = 1
CONNECT BY PRIOR emp_id = mgr_id
ORDER SIBLINGS BY emp_nm

START WITH mgr_id = 1 starts from the two people directly under the CEO, so CONNECT_BY_ROOT tells the division (CTO, CFO) each row belongs to.

NOTE On cyclic data, CONNECT BY stops with ORA-01436: CONNECT BY loop in user data. With NOCYCLE, it does not produce the row that loops back, and flags the row just before it (Dev A in the cyclic data above) with CONNECT_BY_ISCYCLE = 1. The CYCLE clause of recursive WITH differs in that it produces the looped-back row once and flags that row.