Recursive queries
- Version
- 19
- Since
- 8.4
- Review
- Draft
Summary#
WITH RECURSIVE starts from a base query and repeatedly joins the previous step to find more rows. It walks trees and graphs until a step adds nothing.
Syntax#
WITH RECURSIVE name AS (
base_query
UNION ALL
recursive_query_referencing_name
) [SEARCH DEPTH FIRST BY key_column SET order_column]
[CYCLE key_column SET is_cycle USING path_column]
SELECT column_list
FROM name
[ORDER BY sort_column];
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE staff (
staff_id integer PRIMARY KEY,
manager_id integer REFERENCES staff,
name text NOT NULL
);
INSERT INTO staff VALUES
(1, NULL, 'Rin'), (2, 1, 'Sol'), (3, 1, 'Tao'), (4, 2, 'Uma');
WITH RECURSIVE tree AS (
SELECT staff_id, name, 0 AS depth
FROM staff
WHERE manager_id IS NULL
UNION ALL
SELECT s.staff_id, s.name, t.depth + 1
FROM staff AS s
JOIN tree AS t ON s.manager_id = t.staff_id
) SEARCH DEPTH FIRST BY staff_id SET visit_order
SELECT depth, name
FROM tree
ORDER BY visit_order;
-- A graph with a loop: 1 -> 2 -> 3 -> 1.
CREATE TEMPORARY TABLE links (source integer, target integer);
INSERT INTO links VALUES (1, 2), (2, 3), (3, 1);
WITH RECURSIVE walk AS (
SELECT source, target FROM links WHERE source = 1
UNION ALL
SELECT l.source, l.target
FROM links AS l
JOIN walk AS w ON l.source = w.target
) CYCLE source SET is_cycle USING path
SELECT source, target, is_cycle, path
FROM walk
ORDER BY cardinality(path);
ROLLBACK;
Expected output#
depth|name
0|Rin
1|Sol
2|Uma
1|Tao
(4 rows)
source|target|is_cycle|path
1|2|f|{(1)}
2|3|f|{(1),(2)}
3|1|f|{(1),(2),(3)}
1|2|t|{(1),(2),(3),(1)}
(4 rows)
Common mistakes#
With UNION ALL, data that contains a loop can keep the recursion running forever. Add a CYCLE clause or track visited keys yourself. Adding a changing column such as a depth counter also stops plain UNION from recognizing a repeated node. Sort by the column produced by SEARCH to get the requested traversal order.
Version applicability#
PostgreSQL 8.4 added recursive queries. The SEARCH and CYCLE clauses require PostgreSQL 14; earlier versions need explicit path columns for the same work.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0