Recursive CTE SEARCH Breadth First Ordering

Let the database stamp each recursive CTE row with a breadth-first sequence via SEARCH BREADTH FIRST, so level-order output needs no manual depth bookkeeping.

SqlData Integrity

Code

snippet
WITH RECURSIVE tree(id, parent_id, name) AS (
    VALUES
        (1, NULL::int, 'root'),
        (2, 1, 'left'),
        (3, 1, 'right'),
        (4, 2, 'leaf-a'),
        (5, 2, 'leaf-b'),
        (6, 3, 'leaf-c')
),
walk AS (
    SELECT id, parent_id, name, 0 AS depth
    FROM tree
    WHERE parent_id IS NULL

    UNION ALL

    SELECT t.id, t.parent_id, t.name, w.depth + 1
    FROM tree t
    JOIN walk w ON t.parent_id = w.id
) SEARCH BREADTH FIRST BY id SET seq
SELECT seq, depth, name
FROM walk
ORDER BY seq;
-- seq 由数据库按层序自动编号,ORDER BY seq 即逐层展开;
-- DEPTH FIRST 变体同样存在,其 seq 是键值路径数组,适合展开目录树文本

Inside the snippet

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

Breaking the statements into their working parts: 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.

Putting it to use

Run the statement against the tree table.

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`tree`, `walk` — joined via one JOIN clause.