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.

SqlData Integrity

Code

snippet
-- 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 root

What 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

FAQ

Which tables does this file reference?
The references are `folders`, `folder_tree`, with one join tying the pair together.