← Back to PostgreSQL, page 3

postgresql-0043 · Medium mid

Walk a hierarchy with a recursive CTE and use the SEARCH and CYCLE clauses from PostgreSQL 14.

WITH RECURSIVE combines an anchor query with a recursive step. The SEARCH DEPTH FIRST BY clause adds an ordering column for tree-shaped output, and CYCLE ... SET is_cycle USING path detects and stops loops in graph data. Both clauses replace hand-built path arrays used in earlier versions.

Full answer

Test data:

sql
CREATE TABLE categories (id int, parent_id int, name text);
INSERT INTO categories VALUES
  (1, NULL, 'All'), (2, 1, 'Stationery'), (3, 2, 'Pens'), (4, 2, 'Paper'), (5, 1, 'Electronics'), (6, 5, 'Cables');
CREATE TABLE links (src text, dst text);
INSERT INTO links VALUES ('a', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'd');
sql
WITH RECURSIVE tree AS (SELECT id, name, 0 AS depth FROM categories WHERE parent_id IS NULL UNION ALL SELECT c.id, c.name, t.depth + 1 FROM categories c JOIN tree t ON c.parent_id = t.id) SEARCH DEPTH FIRST BY name SET ord SELECT repeat('  ', depth) || name AS outline FROM tree ORDER BY ord;

Result on PostgreSQL 17:

text
    outline
---------------
 All
   Electronics
     Cables
   Stationery
     Paper
     Pens
(6 rows)
sql
WITH RECURSIVE walk AS (SELECT src, dst FROM links WHERE src = 'a' UNION ALL SELECT l.src, l.dst FROM links l JOIN walk w ON l.src = w.dst) CYCLE dst SET is_cycle USING path SELECT src, dst, is_cycle FROM walk ORDER BY path;

Result:

text
 src | dst | is_cycle
-----+-----+----------
 a   | b   | f
 b   | c   | f
 c   | a   | f
 a   | b   | t
 c   | d   | f
(5 rows)

SEARCH DEPTH FIRST orders the output as an indented outline, with children directly under their parent and siblings by name. In the link graph, a to b to c to a is a loop; the walk returns to a, and the CYCLE clause marks the next step, a to b, with is_cycle = true because b is already on the path, and stops following it, so the query ends instead of running forever. Without the clause, UNION ALL recursion on cyclic data runs until it exhausts resources, and UNION only helps when whole rows repeat.

sql
CREATE TABLE categories (id int, parent_id int, name text);
INSERT INTO categories VALUES
  (1, NULL, 'All'), (2, 1, 'Stationery'), (3, 2, 'Pens'), (4, 2, 'Paper'), (5, 1, 'Electronics'), (6, 5, 'Cables');
CREATE TABLE links (src text, dst text);
INSERT INTO links VALUES ('a', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'd');

WITH RECURSIVE tree AS (SELECT id, name, 0 AS depth FROM categories WHERE parent_id IS NULL UNION ALL SELECT c.id, c.name, t.depth + 1 FROM categories c JOIN tree t ON c.parent_id = t.id) SEARCH DEPTH FIRST BY name SET ord SELECT repeat('  ', depth) || name AS outline FROM tree ORDER BY ord;

WITH RECURSIVE walk AS (SELECT src, dst FROM links WHERE src = 'a' UNION ALL SELECT l.src, l.dst FROM links l JOIN walk w ON l.src = w.dst) CYCLE dst SET is_cycle USING path SELECT src, dst, is_cycle FROM walk ORDER BY path;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • WITH RECURSIVE has an anchor and a step
  • SEARCH DEPTH FIRST orders trees
  • CYCLE detects loops
  • Available from PostgreSQL 14
  • Unchecked recursion on cycles never ends

Common mistakes

  • Recursing over graph data without cycle protection
  • Sorting tree output by id

Follow-ups

  • How would you compute the full path string?
  • When would ltree be a better fit?

Tips

  • Show the cycle row