Quick revision
The short answer
WITH RECURSIVE sub AS (SELECT id, name, manager_id, 1 AS depth FROM employees WHERE manager_id = 42 UNION ALL SELECT e.id, e.name, e.manager_id, s.depth + 1 FROM employees e JOIN sub s ON e.manager_id = s.id) SELECT * FROM sub returns everyone under manager 42 with their depth. The anchor runs once and the recursive part runs repeatedly on the previous iteration's rows until it returns none. To survive cycles in bad data we carry a path array and stop when an id repeats, use PostgreSQL 14's CYCLE clause, or add a depth limit, and we index manager_id so each step is an index lookup.
What to remember
In this answer, we wrote a recursive CTE that returns everyone under manager 42 with their depth. The anchor runs once, and the recursive part runs again and again on the rows found by the previous iteration until it finds none. Bad data with a cycle would make it run forever, so we carry a path and refuse repeated ids, use PostgreSQL 14's CYCLE clause, or add a depth limit, and we index manager_id so every iteration is an index lookup instead of a table scan.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
WITH RECURSIVE sub AS (SELECT id, name, manager_id, 1 AS depth FROM employees WHERE manager_id = 42 UNION ALL SELECT e.id, e.name, e.manager_id, s.depth + 1 FROM employees e JOIN sub s ON e.manager_id = s.id) SELECT * FROM sub returns everyone under manager 42 with their depth. The anchor runs once and the recursive part runs repeatedly on the previous iteration's rows until it returns none. To survive cycles in bad data we carry a path array and stop when an id repeats, use PostgreSQL 14's CYCLE clause, or add a depth limit, and we index manager_id so each step is an index lookup.
Why this question is asked
Org charts, folder trees, bills of materials and comment threads are all stored the same way: each row points to its parent. Reading a whole branch of such a tree is one of the most common jobs for a recursive CTE, and one of the easiest ways to bring a database to its knees when the data contains a loop. Interviewers ask for this query because it tests whether we understand how recursion in SQL actually executes, not just the syntax. In this answer, we will recap the adjacency list, write the query and trace its iterations, see what a cycle does to it, add three kinds of protection, and make each iteration fast with an index.
1A Quick Recap of the Adjacency List
Our employees table stores the tree as an adjacency list: each employee row has a manager_id that points at another employee's id. The CEO has manager_id NULL. To find someone's direct reports we look for rows whose manager_id is their id. To find everyone under them, at every level, we have to repeat that step until no new people turn up, and that repetition is what WITH RECURSIVE gives us.
2The Recursive Query
Here is the query with a small sample of data. Manager 42 has two direct reports, one of whom has a report of her own.
The query has two parts joined by UNION ALL. The anchor is the first SELECT; it finds the direct reports of 42 and gives them depth 1. The recursive part is the second SELECT; it refers to sub, the CTE itself, and finds the employees whose manager is someone already found, one level deeper.
3How the Iterations Run
The name sub inside the recursive part does not mean the whole result so far. It means only the rows produced by the previous iteration, which PostgreSQL keeps in a working table. That detail is what makes the process finish.
The database runs the anchor once and puts Ravi and Lena into the result and into the working table. Then it runs the recursive part with sub equal to those two rows and finds Tom. Tom becomes the new working table, and the next run finds Ana. The run after that, with sub equal to Ana alone, finds nobody, the working table is empty, and the recursion stops.
- Run the anchor onceRavi, Lena at depth 1
- Join employees to the working tablefinds Tom at depth 2
- Join again with only Tomfinds Ana at depth 3
- Join again with only Anafinds nobody
- Working table empty?YesStop and return all rowsNoRun the recursive part again
5 steps in order. Play them, or step through them one at a time.
Each iteration sees only the rows found by the previous one.
4What a Cycle Does to the Query
Now suppose a bad data import sets Maya's manager to Ana: 42 reports to 70 and 70 is under 42. The recursion never runs out of rows. After Ana it finds Maya (manager 70), then Maya's reports Ravi and Lena again, and around it goes forever, with depth growing by one each lap.
With UNION ALL, nothing ever stops it. The query runs until it fills temporary disk space or someone cancels it, and in a web request that means a stuck connection and a thread waiting on it. So any recursive query over data we do not fully control needs protection.
5Three Ways to Protect Against Cycles
The most portable fix is to carry the path, the list of ids visited so far on this branch, and refuse to step onto an id that is already in it. In PostgreSQL the path is an array.
Notice what the path does and does not do. It stops every branch the moment it would step onto an id it has already visited, so the query always finishes. It does not stop a node from appearing on two different branches: Ravi shows up at depth 1 and again at depth 5, reached through the bad row for Maya. In practice those odd rows are useful, because they point straight at the bad data, and we can filter them out or add DISTINCT once we have seen them.
PostgreSQL 14 added a standard CYCLE clause that does the same bookkeeping for us. We write CYCLE id SET is_cycle USING path after the CTE body, and PostgreSQL maintains the path column and marks the row where the cycle closes with is_cycle = true without recursing past it. Then SELECT * FROM sub WHERE NOT is_cycle gives the clean result.
The third protection is the depth limit we added above. A real org chart is rarely deeper than 15 levels, so depth < 50 can never cut off real data but always ends a runaway loop. It is cheap and works on every engine, so I add it even when I also track the path.
6Why UNION Is Not Enough, and Indexing manager_id
Some people suggest UNION instead of UNION ALL, because UNION removes duplicate rows and so stops a loop that produces exactly the same row again. That only works when the recursive rows really are identical. Our rows carry depth (and maybe path), which changes on every lap, so no two rows are duplicates and UNION does not stop the cycle. UNION also costs more, because the database has to compare each new row against everything found so far. So UNION is a protection only for queries that select bare ids with no level information.
Performance is the other half of the answer. Each iteration joins employees to the working table on e.manager_id = s.id. Without an index on manager_id, every iteration is a full scan of employees, so a tree 10 levels deep means 10 full scans. With CREATE INDEX ON employees (manager_id), each iteration is a set of index lookups, and the whole query costs roughly the number of rows it returns.
7Follow-up questions
How would you return the path from the CEO as a string?
Start the anchor at the CEO, WHERE manager_id IS NULL, with name::text AS chain, and in the recursive part append the next name: s.chain || ' > ' || e.name. Each row then carries a string like 'Kim > Maya > Lena > Tom'. To get the chain for one employee only, we can walk the tree upwards instead: anchor on WHERE id = 60, recurse with JOIN employees m ON m.id = s.manager_id, and prepend the manager's name at each step, so the walk follows a single line and is cheap.
How do you order the result as a tree, each manager followed by their reports?
Sort by the path. In PostgreSQL an array of ids sorts element by element, so ORDER BY path puts every employee directly after their manager's branch. PostgreSQL 14 also has a SEARCH DEPTH FIRST BY id SET ord clause that builds that ordering column for us.
Does this query work in MySQL?
The basic query works in MySQL 8.0 and later. MySQL has no array type and no CYCLE clause, so the path is usually carried as a string, for example CAST(id AS CHAR(1000)) in the anchor and CONCAT(s.path, ',', e.id) in the recursive part, with FIND_IN_SET(e.id, s.path) = 0 as the guard. MySQL also stops runaway recursion with cte_max_recursion_depth, 1000 by default.
8Conclusion
In this answer, we wrote a recursive CTE that returns everyone under manager 42 with their depth. The anchor runs once, and the recursive part runs again and again on the rows found by the previous iteration until it finds none. Bad data with a cycle would make it run forever, so we carry a path and refuse repeated ids, use PostgreSQL 14's CYCLE clause, or add a depth limit, and we index manager_id so every iteration is an index lookup instead of a table scan.
Open with
I would write WITH RECURSIVE sub as an anchor that selects id, name, manager_id and depth 1 from employees where manager_id is 42, UNION ALL a recursive part that joins employees to sub on e.manager_id equals s.id with depth plus one, and then select from sub.
Then, if they want more
The anchor runs once; the recursive part then runs repeatedly, each time seeing only the rows produced by the previous iteration, and it stops when an iteration returns nothing. Bad data with a loop would make it run forever, so I protect it in two ways.
I carry the path as an array, ARRAY[id] in the anchor and path concatenated with e.id in the recursive part, and add WHERE NOT e.id = ANY(path). On PostgreSQL 14 or later I can use the CYCLE clause instead, which maintains the path and an is_cycle flag for me.
I also add a depth limit like 50 as a safety net. UNION instead of UNION ALL only stops cycles if the rows are exact duplicates, which they are not once there is a depth column, and it is more expensive. Finally I make sure manager_id is indexed, so each iteration is an index lookup rather than a full scan.
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.
- Official documentation
- PostgreSQL documentation, The SQL Language
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 recursive CTE that returns every employee...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/7376986a62/