Quick revision
The short answer
The imported data contains a cycle, for example A reports to B and B reports to A, or someone is their own manager, so walking up the chain never reaches a top person and the recursion never ends. Make the query safe by carrying the visited ids and stopping when an id repeats (PostgreSQL 14+ has CYCLE id SET is_cycle USING path), add a depth limit as a second guard, report the cycle rows so the import can be fixed, and prevent new cycles with a CHECK constraint, import validation and a cycle check on manager changes.
What to remember
In this answer, we saw that a cycle in imported data keeps the recursive CTE producing rows forever, which PostgreSQL ends with statement_timeout and MySQL with its 1000 iteration limit. We made the query safe by tracking visited ids, with an array or the CYCLE clause, and a depth limit, listed the cycle rows for the data owner, and prevented new cycles with a CHECK constraint, import validation and a cycle check that must be serialised to work under concurrency.
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.
The imported data contains a cycle, for example A reports to B and B reports to A, or someone is their own manager, so walking up the chain never reaches a top person and the recursion never ends. Make the query safe by carrying the visited ids and stopping when an id repeats (PostgreSQL 14+ has CYCLE id SET is_cycle USING path), add a depth limit as a second guard, report the cycle rows so the import can be fixed, and prevent new cycles with a CHECK constraint, import validation and a cycle check on manager changes.
Why this question is asked
Recursive queries assume the data is a tree. Real data, especially data imported from another system, does not always respect that assumption, and when it does not, the query runs until something kills it. Interviewers ask this because it combines debugging, SQL technique and data governance: we must recognise the symptom, make the query robust, and stop the problem from coming back. In this answer, we will see why a cycle makes the recursion endless, reproduce it, make the query safe in PostgreSQL and MySQL, find the bad rows, and prevent new cycles, including why a trigger-based check is tricky under concurrency.
1Why a Cycle Makes Recursion Endless
A recursive CTE walking up the management chain keeps joining the current person's manager until a person has no manager, at which point an iteration returns no rows and the query stops. That stop condition depends on every chain reaching someone with manager_id NULL.
If the HR import says Ana reports to Ben and Ben reports to Ana, the chain from Ana goes Ana, Ben, Ana, Ben forever. Each iteration produces exactly one new row, so the working table never empties. PostgreSQL has no built-in limit, so the query runs until statement_timeout cancels it. MySQL stops at cte_max_recursion_depth, 1000 by default, which is the error in the question.
2Reproducing the Problem
Here is the chain query and a tiny data set with one cycle.
7 messages in order. Play them, or step through them one at a time.
The recursion stops only when a step returns no rows, which a cycle prevents.
Notice that Cara is not in the cycle herself; she just reports into it. That is typical: a single bad pair in the import breaks the chain query for everyone below them.
3Making the Query Safe
The robust fix is to remember which ids we have visited on the current path and stop when we meet one again. In PostgreSQL we carry an array of ids and test membership with = ANY. We also mark the row where the cycle closes so it shows up in the output instead of being silently dropped.
The depth < 50 condition is a second, independent guard. No real company has 50 management levels, so reaching it means something is wrong, and the query ends quickly instead of burning resources. In MySQL, which has no arrays, we carry a delimited string such as ',3,1,2,' and test with LOCATE(CONCAT(',', m.id, ','), c.path) = 0, together with the same depth limit.
What about UNION instead of UNION ALL? UNION removes rows identical to rows already found, so with only (id, name, manager_id) columns the second Ana row would be a duplicate and the recursion would stop. But as soon as we carry depth or a path, the repeated rows differ and UNION no longer helps. It is a fragile accident, not a fix.
4Finding the Bad Rows in the Import
A safe query keeps the application running, but the data is still wrong, and every chain report for those people is wrong too. So we list the cycles and hand them to whoever owns the HR data. Starting the cycle-safe walk from every employee and keeping the rows where is_cycle is true gives exactly the ids involved.
The last condition keeps only walks that come back to their own start, which are the members of the cycle, and leaves out people like Cara who merely report into it.
5Preventing New Cycles
The simplest cycle is a person who manages themselves, and a CHECK (manager_id <> id) constraint rules it out for free. Longer cycles need logic. The import job should validate the whole file before applying it, running the cycle query on a staging table and rejecting or quarantining the batch. For changes made through the application, a trigger or a service method walks up from the proposed new manager, and if it reaches the employee being changed, the change would create a cycle and is rejected.
But there is a catch, and it is the usual follow-up. Two concurrent transactions can each make a change that is safe alone but forms a cycle together. Transaction one sets Ana's manager to Ben while transaction two sets Ben's manager to Ana. Each check reads the committed data, sees no cycle and passes, and both commit. This is write skew: they update different rows, so ordinary row locks do not collide. We make it safe by serialising hierarchy changes, for example with a transaction-level advisory lock taken before the check, SELECT ... FOR UPDATE on the rows of the chain, or SERIALIZABLE isolation with a retry on serialization failure.
6Follow-up questions
Why is a cycle check in a trigger hard to make safe under concurrent updates?
Because the check reads rows other transactions may be changing at the same moment. Under READ COMMITTED or REPEATABLE READ, each transaction sees only committed data, so two changes that together form a cycle each pass their check and commit, since they write different rows and never block each other. The fix is to make hierarchy changes take a common lock, such as pg_advisory_xact_lock on a constant key, or to run them at SERIALIZABLE and retry when PostgreSQL reports a serialization failure.
Should we just raise cte_max_recursion_depth in MySQL?
Only if the hierarchy is legitimately deeper than 1000 levels, which an org chart never is. For a cycle, raising the limit just makes the query run longer before failing. The right fix is cycle detection in the query and clean data.
Does a foreign key on manager_id prevent cycles?
No. A foreign key only ensures the manager exists. Ana pointing to Ben and Ben pointing to Ana satisfies both foreign keys perfectly. Cycle prevention needs a check across rows, which constraints in PostgreSQL and MySQL cannot express.
7Conclusion
In this answer, we saw that a cycle in imported data keeps the recursive CTE producing rows forever, which PostgreSQL ends with statement_timeout and MySQL with its 1000 iteration limit. We made the query safe by tracking visited ids, with an array or the CYCLE clause, and a depth limit, listed the cycle rows for the data owner, and prevented new cycles with a CHECK constraint, import validation and a cycle check that must be serialised to work under concurrency.
Open with
The symptom tells me the data has a cycle. A chain query stops only when it reaches someone with no manager, and if the import says A reports to B and B reports to A, or someone manages themselves, every step produces a new row forever.
Then, if they want more
PostgreSQL has no recursion limit so statement_timeout kills it, and MySQL stops at cte_max_recursion_depth, a thousand by default.
To make the query safe, I carry the visited ids in an array, compute a flag that says whether the new id is already in the path, and stop recursing from flagged rows; in PostgreSQL 14 and later the CYCLE id SET is_cycle USING path clause does the same in one line.
I add a depth limit such as fifty as an independent guard, and I return the cycle rows instead of hiding them, because the data is wrong for everyone below the cycle.
I would not rely on UNION instead of UNION ALL, since it only stops cycles when the repeated rows are identical, which breaks as soon as I carry depth or a path.
To prevent it, a CHECK that manager_id differs from id handles self-management, the import job validates the batch for cycles on a staging table before applying it, and application changes check whether the new manager's chain reaches the employee.
That check must be serialised, with an advisory lock or SERIALIZABLE, because two concurrent changes can each pass and together form a cycle.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- 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.
- 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 "A recursive CTE that lists the management chain above an employee runs until PostgreSQL...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/be8ae71ef0/