Intermediate
Open
Pro
A Recursive CTE for Reporting Chains Hangs in Production
Your team has a recursive CTE that, given an employee, finds their entire management chain up to the CEO:
WITH RECURSIVE manager_chain AS (
SELECT employee_id, manager_id, 1 AS level
FROM employees
WHERE employee_id = 4821 -- the starting employee
UNION ALL
SELECT e.employee_id, e.manager_id, mc.level + 1
FROM employees e
JOIN manager_chain mc ON e.employee_id = mc.manager_id
)
SELECT * FROM manager_chain;
This has worked fine in staging for months. In production, run for a
specific employee (employee_id = 4821), it never returns — it hangs
until the connection times out. A SELECT manager_id FROM employees WHERE employee_id = 4821 confirms the row exists and has a normal
manager_id.
- What is the most likely root cause, given that the query works for other employees and worked fine in staging?
- Write a version of the query that would have surfaced this problem immediately with a clear, bounded failure instead of hanging.
- Beyond the query fix, what would you check or fix at the data level, and how would you find every other employee affected by the same issue before it causes another incident?
Share this question