AdvancedCTEs & Recursive

Recursive CTE: category tree with depth

The query

SQL
WITH RECURSIVE cat_tree AS (
  SELECT
    cat_id, name, parent_id, 0 AS depth,
    name::TEXT AS path
  FROM categories
  WHERE parent_id IS NULL

  UNION ALL

  SELECT
    c.cat_id, c.name, c.parent_id,
    ct.depth + 1,
    ct.path || ' > ' || c.name
  FROM categories c
  JOIN cat_tree ct ON c.parent_id = ct.cat_id
)
SELECT
  REPEAT('  ', depth) || name AS tree_view,
  depth,
  path AS full_path
FROM cat_tree
ORDER BY path;
Tested against PostgreSQL 16

Note

Recursive CTE for adjacency list tree. path column builds breadcrumb. Use CYCLE detection for safe graphs.

Tables referenced