Recursive CTE Cycle Detection With CYCLE

Walk a reporting hierarchy whose dirty rows form a loop; the PostgreSQL 14 CYCLE clause flags rows that close a cycle and stops expanding them.

SqlData Integrity

Code

snippet
-- 汇报线里混入脏数据:1 的 manager 是 5,构成 1 → 3 → 5 → 1 的环。
-- UNION ALL 递归遇到环会无限循环,PostgreSQL 14+ 用 CYCLE 子句兜底:
-- 自动维护 path 数组并给成环的行打上 is_cycle,且不再从该行继续展开
WITH RECURSIVE tree(id, parent_id) AS (
    VALUES
        (1, NULL::int),   -- 根节点
        (2, 1),
        (3, 1),
        (5, 3),
        (1, 5)            -- 环源头
),
walk AS (
    SELECT id, parent_id FROM tree WHERE parent_id IS NULL

    UNION ALL

    SELECT t.id, t.parent_id
    FROM tree t
    JOIN walk w ON t.parent_id = w.id
) CYCLE id SET is_cycle USING path
SELECT id, parent_id, is_cycle, path
FROM walk
ORDER BY path;

-- 14 之前的等价写法是手工维护 path 数组:
-- 在递归项里加 WHERE t.id <> ALL(w.path)

What the code does

At its core this is a single SELECT statement against tree and walk.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; a UNION folding the result sets of two queries into one.

Applying it

Run the statement against the tree table.

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
The references are `tree`, `walk`, with one join tying the pair together.