Recursive CTE Depth And Path Tracking

Walk a self-referencing tree table with a recursive CTE, carrying depth and path down the hierarchy and guarding against cycles.

SqlData Integrity

Code

snippet
WITH RECURSIVE subtree AS (
    -- 锚点:根节点
    SELECT
        id,
        parent_id,
        name,
        0 AS depth,
        ARRAY[id] AS path
    FROM categories
    WHERE parent_id IS NULL

    UNION ALL

    -- 递归步:子节点;path 含父 id 时跳过,防止环
    SELECT
        c.id,
        c.parent_id,
        c.name,
        s.depth + 1,
        s.path || c.id
    FROM categories c
    JOIN subtree s ON c.parent_id = s.id
    WHERE NOT c.id = ANY(s.path)
)
SELECT
    repeat('  ', depth) || name AS tree_label,
    depth,
    array_to_string(path, '->') AS lineage
FROM subtree
ORDER BY path;

What the code does

At its core this is a single SELECT statement against categories and subtree.

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 narrowing which rows one statement affects; an ORDER BY that fixes the output order; a UNION combining result sets from separate queries.

Using it

The categories table is the working surface here.

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`categories`, `subtree`, combined through a join.