Sub topic 8
Graphs and Cycle Detection
A hierarchy is a tree: each node has one path from the root. A graph may have several paths, and it may contain a cycle. A cycle is a path that eventually returns to a node already visited, such as 1 → 2 → 3 → 1.
Assume you know SELECT, JOIN, common table expressions, and array or string expressions in your SQL dialect. This chapter uses PostgreSQL syntax because PostgreSQL arrays make the visited path easy to show.
Why cycles matter
A recursive CTE keeps producing rows while its recursive member finds more rows. Without a guard, a cycle can keep producing rows forever or until the database reaches its recursion limit.
The edge table for this graph might look like this:
| src | dst |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
| 2 | 4 |
The query needs to remember which nodes belong to the current path. It must refuse an edge whose destination already appears in that path.
Keep a path and test it
The anchor row starts at node 1. It stores the current node, the path visited so far, and the path length. Each recursive step follows one edge and appends the destination to the path.
WITH RECURSIVE reach(node, path, depth) AS (
SELECT
1,
ARRAY[1],
0
UNION ALL
SELECT
e.dst,
r.path || e.dst,
r.depth + 1
FROM reach AS r
JOIN edges AS e
ON e.src = r.node
WHERE e.dst <> ALL (r.path)
AND r.depth < 100
)
SELECT node, depth, path
FROM reach
ORDER BY depth, node;The expression r.path || e.dst adds the new node to the PostgreSQL integer array. The condition e.dst <> ALL (r.path) means that the destination must differ from every node already visited on this path.
Starting with [1], the query can visit 2, then 3, and then 4. When it considers the edge from 3 back to 1, node 1 is already in [1, 2, 3], so that branch stops.
The depth condition is a second safety measure. Even if the graph has no cycle, a very large or highly branching graph can produce too many rows. A depth limit bounds the work.
UNION versus UNION ALL
UNION ALL is usually the natural choice because each path is meaningful. Two rows with the same node can represent different routes.
UNION removes duplicate rows based on every selected column. If the CTE includes depth or path, repeated visits usually remain different rows, so UNION does not replace a path check. If the CTE contains only a node identifier, UNION can suppress repeated nodes, but then you lose route and depth information and change the meaning of the query.
For reachability only, a recursive CTE with distinct node results may be sufficient. For route reporting, cycle detection, or shortest-path logic, track the path explicitly.
Other path representations
Not every database supports PostgreSQL arrays in recursive CTEs. You can represent a path as:
- A JSON array, with a membership function.
- A delimited string, using delimiters that cannot occur in node IDs.
- A database-specific hierarchy type.
A string test must avoid partial matches. For example, searching for 2 inside 12 would be incorrect unless the path includes safe delimiters.
Exercise
What happens when the recursive query reaches an edge whose destination is already in path?
Show answer
The WHERE condition rejects that row, so that branch stops instead of repeating the cycle.