Union [distinct] within with recursive can be used to omit duplicate rows and thus preventing infinite loops.
WITH RECURSIVE path (a, b) AS (
SELECT edges.* FROM edges
WHERE a = 1
UNION
SELECT edges.* FROM edges
JOIN path
ON edges.a = path.b
)
SELECT *
FROM pathThe example properly terminates even if the graph stored in the edges table has cycles.
Related
Tutorial:
With— Organize Complex QueriesDetect
cyclesby selected key values:cycle…set…to…default…using,cycle…set…to…default,cycle…restrict.Other forms:
with recursive,within subquery,with recursivein subquery.Product specific forms:
connect by.
Normative References
The with recursive clause is defined in ISO/IEC 9075-2:2023 §7.17 as part of optional feature T131, “Recursive query”. Union [distinct] belongs to mandatory feature E071-01.

