- Home
- Interview Questions
- SQL
- How does a recursive CTE execute step by step, and how do yo…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: A recursive CTE runs its anchor query once. It then repeatedly runs the recursive part against only the rows produced in the previous step, and stops when a step returns no rows. To stop infinite loops on cyclic data, track visited keys in a path column, add a depth limit, and rely on engine safeguards such as SQL Server's MAXRECURSION.
Detailed explanation
A recursive CTE has two parts joined by UNION ALL:
- Anchor member: a normal query that does not refer to the CTE. It produces the starting rows, for example the top manager or one specific employee.
- Recursive member: a query that refers to the CTE name once, usually through a join. It produces the next level of rows.
Conceptually, the engine executes it like this:
- Run the anchor. Put its rows into the result and into a temporary working set.
- Run the recursive member, where the CTE name means only the current working set, not the full result so far.
- Append the new rows to the result. These new rows become the working set for the next step.
- Repeat until the recursive member returns zero rows. Then return the accumulated result.
This is why termination depends entirely on your data and your join condition. In a clean tree (each employee has one manager and no one manages themselves indirectly), you eventually reach leaf rows that have no children, and recursion stops. If the data contains a cycle, the working set never becomes empty. Example cycle: A manages B, B manages C, and C manages A.
Syntax differences: PostgreSQL, MySQL 8+ and SQLite require WITH RECURSIVE. SQL Server and Oracle use plain WITH. Oracle requires a column alias list for recursive subquery factoring.
Ways to prevent runaway recursion:
- Path tracking: carry a list of visited IDs and refuse to revisit one. In PostgreSQL this is an array. In SQL Server it is a delimited string. PostgreSQL 14+ also offers a built-in
CYCLEclause. - Depth counter: carry a
depthcolumn, add 1 each step, and filterWHERE depth < Nin the recursive member. This is a cheap safety net even when you expect no cycles. - Engine limits: SQL Server stops at 100 levels by default and raises an error. You can change this with
OPTION (MAXRECURSION n), where 0 means unlimited. MySQL uses thecte_max_recursion_depthvariable (default 1000). PostgreSQL has no default recursion limit, so you must guard the query yourself.
Most engines also restrict what the recursive member may contain. Common restrictions include aggregates, GROUP BY, DISTINCT, LIMIT/TOP and, in SQL Server, outer joins. Exact rules vary by database.
Example
Find everyone under employee 101, at any depth, safely, in PostgreSQL:
WITH RECURSIVE team AS (
-- anchor: the starting employee
SELECT id, name, manager_id,
1 AS depth,
ARRAY[id] AS path
FROM employees
WHERE id = 101
UNION ALL
-- recursive: direct reports of the previous level
SELECT e.id, e.name, e.manager_id,
t.depth + 1,
t.path || e.id
FROM employees e
JOIN team t ON e.manager_id = t.id
WHERE NOT e.id = ANY(t.path) -- cycle guard
AND t.depth < 20 -- depth guard
)
SELECT id, name, depth, path
FROM team
ORDER BY path;In SQL Server, the same idea uses a string path:
CAST('/' + CAST(id AS VARCHAR(20)) + '/' AS VARCHAR(4000)) AS path
...
WHERE CHARINDEX('/' + CAST(e.id AS VARCHAR(20)) + '/', t.path) = 0
...
OPTION (MAXRECURSION 200);The CAST in the anchor matters. SQL Server requires the anchor and recursive columns to have matching types. Without the cast, the string grows and you get a type mismatch error.
Common mistakes
- Assuming the recursive member sees all rows produced so far. It only sees the previous iteration's rows, which explains why each level is joined once.
- Setting
MAXRECURSION 0to silence the error instead of fixing the cyclic data or adding a cycle guard. This can hang the query. - Using
UNIONinstead ofUNION ALLand thinking it prevents cycles. It removes only exact duplicate rows. Once a depth or path column is included, every row is unique and the loop continues. - Putting the depth filter in the outer
SELECT. That filters output but does not stop the recursion itself. The filter must be inside the recursive member.
Follow-up questions
- How would you walk the hierarchy upwards to get an employee's full chain of managers?
- How does a recursive CTE compare with Oracle's
CONNECT BYor a closure table for deep hierarchies? - How would you generate a continuous series of dates with a recursive CTE, and what is a faster alternative?
Interview tip: Explain the anchor, working set and empty-result stopping rule out loud before writing code, then add a depth guard without being asked.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More medium SQL questions
Related Questions
- What is the difference between a view and a materialized view, and when would you use each? · SQL · 1 ans
- How do you fetch the entire row with the highest salary in each department? · SQL · 1 ans
- What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column) in SQL? · SQL · 1 ans
- Why can wrapping an indexed column in a function in WHERE make a query slow? · SQL · 1 ans
- Why does WHERE column = NULL return no rows, and how should you filter NULLs correctly? · SQL · 1 ans
- What are insertion, update and deletion anomalies, and how does normalization prevent them? · SQL · 1 ans
- How does BCNF differ from 3NF, and why can BCNF decomposition lose a dependency? · SQL · 1 ans
- How do ON DELETE CASCADE, SET NULL and RESTRICT work, and when are cascades dangerous? · SQL · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)