UNION Stops Recursive CTE Loops

Cycle-tainted hierarchy walks terminate when the recursive CTE uses UNION: duplicate rows are discarded, so a repeated node produces nothing new.

SqlResilience

Code

snippet
-- 汇报链里有脏数据:ada 的 manager 指回 kim,构成 1 → 3 → 5 → 1 的环(cycle)
CREATE TABLE staff (
    id         int PRIMARY KEY,
    name       text NOT NULL,
    manager_id int
);
INSERT INTO staff VALUES
    (1, 'ada', 5),   -- 脏数据源头
    (2, 'lin', 1),
    (3, 'raj', 1),
    (5, 'kim', 3),
    (4, 'bob', 5);

-- UNION ALL 的递归项每圈都产出新行,环会让查询 loop forever;
-- UNION 对并集去重(dedupe):同一行第二次出现不再是新结果,递归就此 terminate
WITH RECURSIVE reports_under AS (
    SELECT id, name FROM staff WHERE id = 1

    UNION

    SELECT s.id, s.name
    FROM staff s
    JOIN reports_under r ON s.manager_id = r.id
)
SELECT id, name FROM reports_under ORDER BY id;

-- 去重只对“完全相同的行”生效:若 SELECT 列表带不断变化的列(如 depth),
-- UNION 也救不了,得用 PostgreSQL 14+ 的 CYCLE 子句或手工维护 path 数组
DROP TABLE staff;

How it works

Several statements share this file — SELECT / INSERT / CREATE, with staff and reports_under among the objects involved.

In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a UNION combining result sets from separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the staff table.

Statements that matter

WITH RECURSIVE reports_under AS (
    SELECT id, name FROM staff WHERE id = 1
    UNION
    SELECT s.id, s.name
    FROM staff s
    JOIN reports_under r ON s.manager_id = r.id
)
SELECT id, name FROM reports_under ORDER BY id;
INSERT INTO staff VALUES
    (1, 'ada', 5),   -- 脏数据源头
    (2, 'lin', 1),
    (3, 'raj', 1),
    (5, 'kim', 3),
    (4, 'bob', 5);
CREATE TABLE staff (
    id         int PRIMARY KEY,
    name       text NOT NULL,
    manager_id int
);

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
The references are `staff`, `reports_under`, with one join tying the pair together.