SQL Dojo
Pattern

Recursive CTE: trees and hierarchies

A recursive CTE walks a tree to any depth: the subcategories of a category, everyone under a manager, the parts inside a part.

You need it when a table points to itself: categories with a parent, employees with a manager, parts made of other parts. A self-join goes down one level; a recursive CTE goes down as many levels as there are.

WITH RECURSIVE tree AS (
  SELECT category_id, name, 1 AS depth
  FROM categories
  WHERE parent_category_id IS NULL
  UNION ALL
  SELECT c.category_id, c.name, t.depth + 1
  FROM categories c
  JOIN tree t ON c.parent_category_id = t.category_id
)
SELECT * FROM tree;

The anchor (the first SELECT) runs once and gives the top categories. The recursive member reads tree itself: each round, it finds the children of the rows the previous round added, and the recursion stops when a round adds none.

The trap. A loop in the data (an employee who is, through others, their own manager) and the query never ends, or stops at an engine limit after a long wait. Give the recursive member a guard: a maximum depth (WHERE t.depth < 20), or the path so far, refusing a node already on it.

On your warehouse. Postgres and BigQuery require the word RECURSIVE; Snowflake accepts it but does not need it. Databricks runs recursive CTEs only on recent runtimes (since 2025). On Postgres, cast a text column that grows in the recursion in the anchor (CAST(name AS TEXT)): otherwise its type differs between the two halves, and the query fails.

WITH RECURSIVE tree AS (
  SELECT category_id, name, 1 AS depth, CAST(name AS VARCHAR) AS path
  FROM categories
  WHERE name = 'Drinks'
  UNION ALL
  SELECT c.category_id, c.name, t.depth + 1, t.path || ' > ' || c.name
  FROM categories c
  JOIN tree t ON c.parent_category_id = t.category_id
)
SELECT category_id, depth, path
FROM tree
ORDER BY path;
category_iddepthpath
141Drinks
12Drinks > Coffee
63Drinks > Coffee > Capsules
43Drinks > Coffee > Coffee beans
53Drinks > Coffee > Ground coffee
22Drinks > Tea
83Drinks > Tea > Black tea
73Drinks > Tea > Green tea
93Drinks > Tea > Herbal teas
Try it in Randori