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.
Code
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
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.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.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.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.
FAQ
- Which tables or CTEs does it reference?
- `categories`, `subtree`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.