Paths Subjects Questions Quizzes Pricing Search
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.

  1. What is the most likely root cause, given that the query works for other employees and worked fine in staging?
  2. Write a version of the query that would have surfaced this problem immediately with a clear, bounded failure instead of hanging.
  3. 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

← Back to Advanced SQL: Window Functions & CTEs practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.