Scrivio Interview library
CodingIntermediate9 min read · updated 12 November 2026

Table employees(id, name, manager_id). Write a PostgreSQL query that returns the full reporting chain under a given manager with depth, and protect it against cycles in bad data.

We use a recursive CTE: the first part selects the direct reports of the given manager at depth 1, and the recursive part joins employees to the rows found so far on e.manager_id = c.id, adding 1 to the depth each round. To survive cycles in bad data we either add PostgreSQL's CYCLE clause (PostgreSQL 14 and later), carry an array path and refuse ids already on it, or cap the depth, and we index manager_id so every round is a cheap index probe.

Why this question is asked

Org charts, category trees, bill-of-materials tables and comment threads are all stored the same way: each row points at its parent. Sooner or later someone asks for everything under one node, and a plain join only reaches one level. Interviewers like this question because it tests whether we know recursive SQL and, more importantly, whether we think about what happens when the data is wrong, because a single bad update that makes two people manage each other turns a naive query into one that never ends. In this answer, we will recap how a self-referencing table works, write the recursive query step by step, break it with a cycle, protect it three different ways, and finish with indexing and the alternative tree models for heavy use.

1A Quick Recap of Self-Referencing Tables

The employees table refers to itself. Each row has an id, a name and a manager_id, and manager_id holds the id of another row in the same table. The person at the top has manager_id NULL. A self join, a join of a table with itself under two aliases, can find one level: the people whose manager_id equals a given id. A second join finds the level below that, and so on, but we do not know in advance how many levels there are.

A recursive CTE solves that. A CTE (common table expression) is a named subquery written with WITH. The recursive form, WITH RECURSIVE, has two parts joined by UNION ALL: an anchor query that produces the starting rows, and a recursive query that refers to the CTE's own name and produces the next rows from the rows found in the previous round. PostgreSQL repeats the recursive part until a round returns no rows.

2Writing the Recursive Query

Here is a small data set and the query for everyone under Ada (id 1).

SQL
CREATE TABLE employees (id int PRIMARY KEY, name text NOT NULL, manager_id int REFERENCES employees(id));
INSERT INTO employees VALUES
(1, 'Ada', NULL), (2, 'Ben', 1), (3, 'Cy', 1), (4, 'Dee', 2), (5, 'Eve', 4);
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 1 AS depth
FROM employees
WHERE manager_id = 1 -- anchor: direct reports of the root
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id -- recursive step: reports of the last round
)
SELECT id, name, depth FROM chain ORDER BY depth, name;
-- 2 | Ben | 1
-- 3 | Cy | 1
-- 4 | Dee | 2
-- 5 | Eve | 3
Step throughHow PostgreSQL evaluates WITH RECURSIVE
  1. Run the anchor queryBen, Cy at depth 1
  2. Put the rows in the result and the working table
  3. Run the recursive part against the working table onlyfinds Dee, then Eve
  4. Did this round return any rows?
    YesMake them the new working table and repeatNoStop and return the result

4 steps in order. Play them, or step through them one at a time.

Notice how the rounds work. The anchor returns Ben and Cy at depth 1. The first recursive round joins employees to those two rows and finds Dee, whose manager is Ben, at depth 2. The next round finds Eve under Dee at depth 3. The round after that finds nobody whose manager is Eve, returns no rows, and the recursion stops. In the recursive part, chain only means the rows of the previous round, not the whole result so far, which is why each round does a small join.

3What a Cycle Does to It

Now suppose a bad import sets Ada's manager_id to 5, so Ada reports to Eve, who reports up to Ada. The rows form a loop. Run the same query again and it never finishes: Eve's reports now include Ada, Ada's reports include Ben and Cy again, and the depth keeps growing. The query runs until it fills temporary space or someone cancels it.

SQL
UPDATE employees SET manager_id = 5 WHERE id = 1; -- bad data: Ada now reports to Eve
-- the query above now returns Ben, Cy, Dee, Eve, Ada, Ben, Cy, Dee, Eve, Ada, ... forever

One might think that switching UNION ALL to UNION fixes it, since UNION throws away rows it has seen before. But there is a catch: UNION compares whole rows, and depth makes every row different (Ben at depth 1 is not equal to Ben at depth 6), so duplicates are never found. UNION only stops a cycle when the rows carry no changing column. It also costs real work: PostgreSQL must keep every row produced so far in a hash table and check each new row against it, every round. So we need a real guard.

4Fix 1: The CYCLE Clause

PostgreSQL 14 added the SQL standard CYCLE clause. We name the column that identifies a row, and PostgreSQL tracks the path for us.

SQL
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 1 AS depth FROM employees WHERE manager_id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e JOIN chain c ON e.manager_id = c.id
) CYCLE id SET is_cycle USING path
SELECT id, name, depth, is_cycle FROM chain;
-- 2 | Ben | 1 | f
-- 3 | Cy | 1 | f
-- 4 | Dee | 2 | f
-- 5 | Eve | 3 | f
-- 1 | Ada | 4 | f
-- 2 | Ben | 5 | t -- Ben is already on the path: marked, and the recursion stops here

CYCLE id SET is_cycle USING path adds two hidden columns. path holds the ids visited on the way to each row, and is_cycle becomes true for the row that repeats an id already on its path. PostgreSQL does not expand rows marked as a cycle, so the query ends. The repeating row itself is still returned, so we usually add WHERE NOT is_cycle in the outer query, or keep it and report it, which is a nice way to find the bad data. A companion SEARCH DEPTH FIRST BY id SET ord clause gives an ordering column if we want the result in tree order.

5Fix 2: An Array Path, and Fix 3: A Depth Limit

On older versions, or when we want full control, we build the path ourselves as an array and refuse any id that is already on it. Seeding the path with the root as well as the first id also stops the root from showing up under itself.

SQL
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 1 AS depth, ARRAY[manager_id, id] AS path
FROM employees WHERE manager_id = 1
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1, c.path || e.id
FROM employees e JOIN chain c ON e.manager_id = c.id
WHERE NOT e.id = ANY(c.path) -- refuse anyone already on this branch
AND c.depth < 30 -- and never go deeper than a real org chart can be
)
SELECT id, name, depth FROM chain ORDER BY depth, name;
-- 2 | Ben | 1
-- 3 | Cy | 1
-- 4 | Dee | 2
-- 5 | Eve | 3 -- Ada (id 1) is on the path, so the loop ends here

The array check is exact: it stops at the first repeat on each branch. The depth limit is a blunt safety net. It does not detect a cycle, it just caps the damage, so with only a depth limit we would get the loop repeated up to 30 levels. Using both is cheap and means a future data bug can never produce a runaway query. The cost of the array grows with depth, which is fine for org charts that are rarely more than 10 or 15 levels deep.

6Making It Fast: Indexes and Other Tree Models

Each round of the recursion looks up rows by manager_id. Without an index, every round is a full scan of employees, so a 12-level chart on a 200,000-row table means 12 full scans. With CREATE INDEX ON employees (manager_id), each round becomes a set of index probes that touch only the rows it returns. The primary key on id does not help here, because we search by the parent, not by the row's own id.

If the subtree query runs constantly, for example on every page view of a large category tree, recursion on every request can still be too much. Then we change the storage model. A closure table stores every ancestor-descendant pair, so the subtree is one indexed join. PostgreSQL's ltree extension stores the path as a value such as 1.2.4 and answers 'everything under 1.2' with a prefix test on a GiST index. Nested sets store left and right numbers so a subtree is a range check, but every insert renumbers many rows. Each trades write cost for read speed, and for an org chart that changes daily, the recursive CTE with an index is usually the right answer.

7Follow-up questions

Why not just load the table into Java and walk the tree there?

For a few thousand rows it works and is simple: one query, a Map from manager id to reports, and a loop with a visited set. It stops being a good idea when the table is large, when we only need a small subtree, or when the result feeds another query, because we pull every row over the network to use a few of them. The recursive CTE keeps the work in the database, returns only the subtree, and can be joined to other tables in the same statement.

Does MySQL support the same query?

MySQL 8.0 supports WITH RECURSIVE with the same anchor and recursive parts, but it has no CYCLE clause. We build the path as a string, for example CONCAT(path, ',', e.id), and stop with FIND_IN_SET(e.id, path) = 0, plus a depth limit. MySQL also stops any recursive CTE after cte_max_recursion_depth rounds, 1000 by default, and raises an error, which is a safety net rather than a cycle check. The string column needs a wide enough type, so we cast the anchor's path to a CHAR of sufficient length.

Should we also prevent cycles from being written?

Yes, if we can. A CHECK constraint cannot look at other rows, so the usual protection is in the write path: before changing a manager, the service checks that the new manager is not in the employee's own subtree, using the same recursive query, inside the same transaction with a lock on the rows involved. The query guard is still worth keeping, because data also arrives through imports and scripts that skip the service.

8Conclusion

In this answer, we saw how WITH RECURSIVE builds the reporting chain round by round from an anchor and a recursive join on manager_id, how a single bad row makes it loop forever, and why UNION alone does not help once depth is in the row. We protected the query with the CYCLE clause, with an array path checked by ANY, and with a depth limit, indexed manager_id so each round is a probe, and noted that closure tables, ltree or nested sets fit trees that are read far more than they change.

What to say in the interviewAbout 100 seconds aloud

Open with

I would write a recursive CTE. The anchor selects the direct reports, WHERE manager_id equals the root, with depth 1. The recursive part joins employees to the CTE on e.manager_id = c.id and adds one to the depth, and the two are combined with UNION ALL.

Then, if they want more

PostgreSQL runs the recursive part against the rows of the previous round until a round returns nothing.

The danger is bad data: if two people end up managing each other, the query never stops, and switching to UNION does not save us because the depth column makes every row distinct, and it costs a hash of all rows per round anyway.

On PostgreSQL 14 or later I would add CYCLE id SET is_cycle USING path, which marks the repeated row and stops expanding it, then filter on NOT is_cycle, or report those rows to find the bad data. On older versions I carry an array path, seeded with the root and the first id, and add WHERE NOT e.id = ANY(c.path).

I also add a depth limit like 30 as a cheap safety net. For performance I make sure there is an index on manager_id, because every round searches by the parent.

If this subtree query is very hot, for example on a big category tree, I would consider a closure table or ltree so reads do not need recursion at all, but for an org chart that changes often the recursive query with an index is the right tool.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 14, MySQL 8.0
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Table employees(id, name, manager_id). Write a PostgreSQL query that returns the full...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/8c3b15f368/