Design a query to identify circular references in a hierarchical employee structure.
Instruction: For PostgreSQL employee(employeeid integer PRIMARY KEY, managerid integer), identify employees in indirect reporting cycles of length at least two. Ensure recursion terminates. Distinguish cycle members from employees whose manager chain merely enters a cycle.
Updated
Official answer
Assume PostgreSQL employee(employeeid integer PRIMARY KEY, managerid integer). Follow the manager chain from every employee, carrying visited IDs. Report only a start node whose chain returns to itself:
WITH RECURSIVE walk AS (
SELECT employeeid AS start_id, employeeid AS current_id,
managerid AS next_id, ARRAY[employeeid] AS path
FROM employee
UNION ALL
SELECT w.start_id, e.employeeid, e.managerid, w.path || e.employeeid
FROM walk AS w
JOIN employee AS e ON e.employeeid = w.next_id
WHERE NOT e.employeeid = ANY(w.path)
)
SELECT DISTINCT start_id AS employee_id
FROM walk
WHERE next_id = start_id AND cardinality(path) > 1
ORDER BY employee_id;
For 1→2→1 and 3→1, this returns 1 and 2, not 3: employee 3 reaches a cycle but never reports back to itself. The path condition stops repeated visits, so cycles cannot recurse forever. A NULL or missing manager terminates that path.
The cardinality condition excludes direct self-links because the question asks about indirect cycles. Remove it to include those too. Starting from every employee can be expensive for a large hierarchy; use an appropriate diagnostic environment and prevent new cycles through a concurrency-safe write policy rather than relying only on periodic detection.