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.
Code
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
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.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- What are the relations in play here?
- `tree`, `walk` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.