Recursive CTE SEARCH Depth First Ordering
SEARCH DEPTH FIRST BY sets the sequence column to each row key path, emitting parents before children so trees unfold in pre-order without hand-managed state.
Code
-- PG 14+: SEARCH DEPTH FIRST BY ... SET ... produces a "key-path array" sort column
-- Recursion expands a parent first with its subtrees immediately after: preorder without hand-kept state
WITH RECURSIVE folder_tree AS (
SELECT id, parent_id, name
FROM folders
WHERE parent_id IS NULL
UNION ALL
SELECT f.id, f.parent_id, f.name
FROM folders f
JOIN folder_tree t ON f.parent_id = t.id
) SEARCH DEPTH FIRST BY id SET preorder
SELECT id, parent_id, name, preorder
FROM folder_tree
ORDER BY preorder;
-- preorder looks like {1,2,4}: the whole ancestor path lives inside,
-- array_length(preorder, 1) is the depth, preorder[1] is the rootWhat the code does
At its core this is a single SELECT statement against folders and folder_tree.
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.
Applying it
Run the statement against the folders table.
Statements that matter
WITH RECURSIVE folder_tree AS (
SELECT id, parent_id, name
FROM folders
WHERE parent_id IS NULL
UNION ALL
SELECT f.id, f.parent_id, f.name
FROM folders f
JOIN folder_tree t ON f.parent_id = t.id
) SEARCH DEPTH FIRST BY id SET preorder
SELECT id, parent_id, name, preorder
FROM folder_tree
ORDER BY preorder;
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
- Which tables does this file reference?
- The references are `folders`, `folder_tree`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.