1. Home
  2. Interview Questions
  3. SQL
  4. 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

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best 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:

  1. Run the anchor. Put its rows into the result and into a temporary working set.
  2. Run the recursive member, where the CTE name means only the current working set, not the full result so far.
  3. Append the new rows to the result. These new rows become the working set for the next step.
  4. 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 CYCLE clause.
  • Depth counter: carry a depth column, add 1 each step, and filter WHERE depth < N in 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 the cte_max_recursion_depth variable (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 0 to silence the error instead of fixing the cyclic data or adding a cycle guard. This can hang the query.
  • Using UNION instead of UNION ALL and 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 BY or 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

All medium questions →

Related Questions

‹
Q5 of 10 · SQL
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA