Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Table employee(id int primary key, name text, manager_id int null). Write a query that returns everyone who reports directly or indirectly to employee 7, with their depth below 7 and the path of names from 7 to them.

Use a recursive CTE: the anchor selects the people whose manager_id is 7 with depth 1 and their own name as the path, and the recursive part joins employees whose manager is a row already found, adding 1 to the depth and appending the name to the path. UNION ALL keeps it fast, and an index on manager_id turns each level into an index lookup.

Why this question is asked

Org charts, category trees, bills of materials and folder structures are all stored the same way in relational databases: each row points to its parent. Sooner or later someone asks for everything below a node, and the answer is a recursive query. Interviewers ask this to check that we can write one from memory and that we understand how it executes, because that understanding is what lets us debug the slow or never-ending versions later. In this answer, we will recap the adjacency list model, write the query, follow its execution level by level, look at the MySQL differences and finish with indexing.

1A Quick Recap of the Adjacency List

The table stores the hierarchy as an adjacency list: every employee row has a manager_id pointing to another row of the same table, and the top person has NULL. It is simple and cheap to change, since moving a person means updating one value.

The cost shows up on reads. Finding direct reports of 7 is one query, but finding reports of reports needs another query per level, and we do not know in advance how many levels there are. A recursive CTE lets the database repeat that step for us until no new rows appear.

2Writing the Recursive Query

A recursive CTE has two parts joined by UNION ALL. The anchor member runs once and gives the starting rows. The recursive member refers to the CTE itself and runs again and again, each time on the rows produced by the previous step.

SQL
-- 7 Maria, 12 Ana (mgr 7), 15 Ben (mgr 7), 21 Chen (mgr 12), 30 Dev (mgr 21)
WITH RECURSIVE r AS (
SELECT id, name, 1 AS depth, name::text AS path
FROM employee
WHERE manager_id = 7 -- anchor: direct reports
UNION ALL
SELECT e.id, e.name, r.depth + 1, r.path || ' > ' || e.name
FROM employee e
JOIN r ON e.manager_id = r.id -- recursive: reports of the last level
)
SELECT id, name, depth, path FROM r ORDER BY path;
-- 12 | Ana | 1 | Ana
-- 21 | Chen | 2 | Ana > Chen
-- 30 | Dev | 3 | Ana > Chen > Dev
-- 15 | Ben | 1 | Ben

The question asks for the path from 7 to each person. If we want Maria at the front, we start the anchor path as 'Maria > ' || name, or join the employee 7 row into the anchor. The cast name::text matters: in PostgreSQL the column types of the CTE are fixed by the anchor, and an explicit text type avoids a type mismatch when the recursive part produces longer concatenated strings.

3How the Database Executes It

It helps to picture a working table. The anchor fills it with level 1. Each iteration runs the recursive member against only the rows from the previous iteration, not the whole result so far, adds the new rows to the result and makes them the next working table. When an iteration produces no rows, recursion stops.

Step throughIterations of the recursive CTE
  1. Anchor: manager_id = 7Ana, Ben (depth 1)
  2. Join employees whose manager is Ana or BenChen (depth 2)
  3. Join employees whose manager is ChenDev (depth 3)
  4. Join employees whose manager is Devno rows
  5. No new rows?
    Yesstop and return all rowsNorepeat with the new rows

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

The reason UNION ALL is the right choice is that UNION would compare every new row with everything already found to remove duplicates, which costs time and memory and is never needed in a proper tree, where each person appears exactly once.

4The Same Query in MySQL 8

MySQL 8 supports WITH RECURSIVE with the same structure, with two practical differences. String concatenation is CONCAT(), because || means OR by default in MySQL. And the type of each column is taken from the anchor, so a path that starts as a short name can be truncated or fail with a data too long error in strict mode as it grows. We widen it in the anchor with a cast.

SQL
WITH RECURSIVE r AS (
SELECT id, name, 1 AS depth, CAST(name AS CHAR(1000)) AS path
FROM employee WHERE manager_id = 7
UNION ALL
SELECT e.id, e.name, r.depth + 1, CONCAT(r.path, ' > ', e.name)
FROM employee e JOIN r ON e.manager_id = r.id
)
SELECT * FROM r;

MySQL also has a safety net: the cte_max_recursion_depth system variable, 1000 by default, aborts a recursive CTE that goes deeper than that. A real org chart is rarely more than 15 levels deep, so hitting the limit almost always means bad data with a cycle, not a deep company.

5Indexing for Each Level

Each iteration asks the same question: which employees have a manager_id in this set of ids. Without an index on manager_id, that is a full scan of the employee table per level, so a five-level tree means five full scans. With CREATE INDEX ON employee (manager_id), each level becomes a set of index lookups, and the query touches only the rows it returns.

Notice that PostgreSQL does not create indexes for foreign keys automatically; only the referenced primary key is indexed. So an employee table with a manager_id foreign key often lacks exactly the index this query needs.

6Follow-up questions

How would you list the chain of managers above an employee instead?

Reverse the direction of the join. The anchor selects the employee itself, and the recursive member joins the employee whose id equals the manager_id of the last row: SELECT m.id, m.name, m.manager_id, r.depth + 1 FROM employee m JOIN chain r ON m.id = r.manager_id. Each level is now a primary key lookup, and the recursion stops at the top person, whose manager_id is NULL.

Why does the recursive member only see the previous level?

That is how the standard defines the evaluation: the working table holds only the rows produced by the last iteration. It keeps each step small and prevents the query from rediscovering rows it already found, which is also why a cycle in the data makes it loop forever instead of stopping.

How do you return the result in tree order?

Ordering by the text path gives a readable depth-first order, but names that share a prefix can sort oddly. A more reliable way is to carry an array of ids or of zero-padded sort keys in PostgreSQL and order by that array. PostgreSQL 14 also offers SEARCH DEPTH FIRST BY id SET ordercol for this.

7Conclusion

In this answer, we wrote a recursive CTE whose anchor selects the direct reports of employee 7 and whose recursive member repeatedly joins the next level by manager_id, carrying depth and a name path. We followed the execution level by level until no rows remained, saw why UNION ALL is preferred, adapted it for MySQL 8 with CONCAT and a wide path type, and indexed manager_id so each level is an index lookup.

What to say in the interviewAbout 90 seconds aloud

Open with

I would use a recursive CTE. The anchor member selects id, name, depth 1 and the name cast to text as the path, from employee where manager_id is 7, so those are the direct reports.

Then, if they want more

Then UNION ALL with the recursive member, which joins employee e to the CTE on e.manager_id equals r.id, selecting depth plus one and the path concatenated with an arrow and the new name. The database runs the anchor once, then repeatedly runs the recursive part against only the rows found in the previous iteration, until an iteration returns nothing.

I use UNION ALL rather than UNION because in a tree there are no duplicates, so deduplication is pure cost. In PostgreSQL I cast the path in the anchor because the anchor fixes the column types.

MySQL 8 supports WITH RECURSIVE too; I would use CONCAT and cast the path to a wide CHAR in the anchor, and its cte_max_recursion_depth, a thousand by default, stops runaway recursion, which in practice signals a cycle in the data.

For performance, I would index manager_id, because every iteration asks which employees report to a set of ids, and without that index each level is a full table scan. PostgreSQL does not index foreign key columns automatically, so this is easy to miss.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8, PostgreSQL 14
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 employee(id int primary key, name text, manager_id int null). Write a query that...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/252fb616bf/