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.
Code
-- 汇报线里混入脏数据: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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- The references are `tree`, `walk`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.