Avoiding Infinite Recursion
Cycle detection, depth limits, and the recursion guard every interviewer checks for.
The Question Behind the Question
After you write a recursive CTE, a sharp interviewer asks: "What happens if the data has a cycle?" This checks whether you understand that recursion can run forever — and whether you know how to guard against it.
A cycle is when the hierarchy loops back on itself: A reports to B, B reports to A. The naive recursive member will bounce between them indefinitely.
How a Cycle Forms
Trees are supposed to be acyclic, but real data is messy. A bad update can set an employee as their own (indirect) manager. A graph — like "users who follow users" — is cyclic by nature.
When the recursive member re-encounters a node it already visited, it produces that node again, which re-triggers its children, and the loop never empties. Recursion only stops when a step returns no rows; a cycle guarantees it always returns rows.
All lessons in this course
- Anchor and Recursive Members
- Traversing an Org Chart
- Generating Number and Date Series
- Avoiding Infinite Recursion