Walking hierarchies

A hierarchy, such as an org chart or a category tree, is stored with a parent column referencing the same table. A recursive CTE walks it starting from the root, following the parent-child links, and can compute the level or path of each node.

Example

WITH RECURSIVE arbre AS (
  SELECT id, parent_id, 0 AS niveau FROM categories WHERE parent_id IS NULL
  UNION ALL
  SELECT c.id, c.parent_id, a.niveau + 1 FROM categories c JOIN arbre a ON c.parent_id = a.id
)
SELECT * FROM arbre;

Related concepts

The whole glossary