Sub topic 10
UNION versus UNION ALL inside recursion
This chapter assumes you can write a basic recursive CTE (anchor member, recursive member, UNION ALL). It also assumes you know how the working table drives each iteration, and that you are comfortable with self-joins and GROUP BY. Here you will learn what changes when the two members are joined with UNION instead of UNION ALL. You will also learn when each choice is correct and which databases accept which.
What the set operator controls
The operator between the anchor member and the recursive member does two jobs. It combines the rows into the final result, and it decides which rows from each iteration are kept for the next one.
UNION ALLkeeps every row the recursive member produces. Each iteration's output becomes the next iteration's working table unchanged.UNION(also writtenUNION DISTINCTin some dialects) discards a new row if an identical row has already been produced. In PostgreSQL, the manual says it discards duplicates and rows that duplicate any previous result row. The comparison is therefore against everything accumulated so far, not just the current iteration. Rows discarded this way never reach the working table.
The second point is what makes UNION more than a cosmetic choice. A row that is dropped is never expanded, so the branch of the search behind it stops growing.
With UNION ALL, the Already in result? check does not exist, so the only way out is for the recursive member to return no rows.
Duplicates caused by converging paths
Duplicates appear even in graphs with no cycles. If two routes lead to the same node, UNION ALL reaches that node twice and expands it twice. The code below builds a small diamond-shaped graph and runs both variants.
CREATE TABLE dag_edges (src INT, dst INT);
INSERT INTO dag_edges (src, dst) VALUES
(1, 2), (1, 3), (2, 4), (3, 4), (4, 5);
-- UNION ALL: node 4 and node 5 each appear twice
WITH RECURSIVE reach(node) AS (
SELECT dst FROM dag_edges WHERE src = 1
UNION ALL
SELECT e.dst
FROM dag_edges e
JOIN reach r ON e.src = r.node
)
SELECT node FROM reach ORDER BY node;
-- UNION: each node appears once
WITH RECURSIVE reach(node) AS (
SELECT dst FROM dag_edges WHERE src = 1
UNION
SELECT e.dst
FROM dag_edges e
JOIN reach r ON e.src = r.node
)
SELECT node FROM reach ORDER BY node;The first query returns 2, 3, 4, 4, 5, 5. The anchor produces 2 and 3. The first iteration reaches 4 from both, giving two copies. The second iteration expands both copies and gives two copies of 5. The second query returns 2, 3, 4, 5. In the first iteration the second copy of 4 is a duplicate of the first and is dropped, so only one row is expanded.
This effect compounds. If a graph has layers of diamonds, the number of rows under UNION ALL doubles with each layer, because it equals the number of distinct paths. The number of distinct nodes grows only linearly. UNION keeps the work proportional to the nodes reached.
UNION as a termination mechanism
Because UNION refuses rows it has already seen, it can stop a cycle without any extra bookkeeping. The edges below contain the cycle 1, 2, 3, 1.
CREATE TABLE edges (src INT, dst INT);
INSERT INTO edges (src, dst) VALUES
(1, 2), (2, 3), (3, 1), (3, 4);
WITH RECURSIVE reach(node) AS (
SELECT dst FROM edges WHERE src = 1
UNION
SELECT e.dst
FROM edges e
JOIN reach r ON e.src = r.node
)
SELECT node FROM reach ORDER BY node;This returns 1, 2, 3, 4. The iterations go like this:
- The anchor yields 2.
- Expanding 2 yields 3.
- Expanding 3 yields 1 and 4.
- Expanding 1 yields 2, which is a duplicate and is dropped. Expanding 4 yields nothing.
- The working table is empty, so the query stops.
Replace UNION with UNION ALL and the query never ends, because 2 is re-emitted forever. The query runs until you cancel it or the server runs out of memory or disk.
This explains a common design tension. You often want depth or path in the output, but those columns defeat deduplication. There are three ways to handle it.
| Goal | Approach |
|---|---|
| Reachable nodes only | `UNION` with just the node columns |
| Every distinct path | `UNION ALL` with a path column and a visited check, as in the cycle-detection chapter |
| Shortest hop count per node | `UNION ALL` with a depth cap, then `MIN(depth)` in the outer query |
The third approach looks like this:
WITH RECURSIVE hops(node, depth) AS (
SELECT dst, 1 FROM edges WHERE src = 1
UNION ALL
SELECT e.dst, h.depth + 1
FROM edges e
JOIN hops h ON e.src = h.node
WHERE h.depth < 6
)
SELECT node, MIN(depth) AS shortest
FROM hops
GROUP BY node
ORDER BY node;The depth < 6 cap guarantees termination, and the outer GROUP BY collapses the duplicates. The result is correct (2 at depth 1, 3 at depth 2, 1 and 4 at depth 3), but the query still generates rows along every path up to the cap. On a large cyclic graph it can do far more work than a plain UNION reachability query.
Choosing between them
Use UNION ALL when:
- the data is a true tree (each row has one parent) or a series, so duplicates cannot occur;
- you want every path, or need columns such as depth or path that differ per row;
- you want the cheapest execution, since no duplicate check is needed.
Use UNION when:
- the question is "which nodes are reachable?" and the graph may have cycles or converging paths;
- the CTE's columns identify the thing you are visiting and nothing else.
UNION ALL is the default for good reason. Deduplication requires the database to remember every row produced, usually in a hash table or a sorted structure. That costs memory and CPU on every iteration, and the cost grows with the result. For a tree, the check never removes anything, so it is pure overhead.
Duplicates within the anchor
Deduplication also applies to the anchor member. If the anchor query can return the same row twice, UNION collapses the copies before the first iteration. With UNION ALL both copies are expanded, and every descendant appears twice. When a recursive result contains unexpected double counts, check the anchor first.
Comparison follows UNION rules. Two NULL values count as equal, and every selected column is compared. A row is a duplicate only if all columns match.
Dialect support
Not every database accepts both forms.
| Database | `UNION ALL` | `UNION` |
|---|---|---|
| PostgreSQL | Yes | Yes |
| MySQL 8 | Yes | Yes |
| SQLite | Yes | Yes |
| SQL Server | Yes | Not allowed |
SQL Server requires a top-level UNION ALL between the anchor and the recursive member. Using UNION raises an error saying the CTE does not contain a top-level UNION ALL operator. Oracle's recursive WITH form also expects UNION ALL.
You might try to rebuild UNION behavior by hand, for example with WHERE NOT EXISTS (SELECT 1 FROM reach ...) in the recursive member. Most databases reject this, because the recursive reference may not appear inside a subquery (PostgreSQL and SQL Server both refuse it). On those platforms, track visited nodes in a path column inside the row itself, as shown in the cycle-handling chapter. Alternatively, cap the depth and deduplicate in the outer query.
Summary of failure modes
- Infinite loop with
UNION ALLon cyclic data. Fix it by switching toUNION, or by adding a path check or a depth cap. - Infinite loop with
UNIONplus a depth or path column. Every row looks unique. Remove the extra column or add an explicit stop condition. - Inflated counts with
UNION ALLon a graph with converging paths. Each path produces its own copy. UseUNIONif you want nodes, or aggregate if you want path counts. - Memory growth with
UNIONon huge results. The database must keep every row it has seen. Narrow the selected columns to the identifying key.
Exercise
A query uses UNION and returns columns node and depth, with depth + 1 computed in the recursive member. The data contains a cycle, and the query never finishes. Why does UNION not stop it, and what are two ways to fix it?
Show answer
Each trip around the cycle produces a larger depth, so the row (node, depth) is never identical to an earlier row and UNION never drops it. One fix is to remove depth from the CTE and use UNION on node alone. The other is to keep depth, use UNION ALL, and add WHERE depth < N (or a visited-path check) to the recursive member.
Exercise
Given the diamond graph dag_edges with edges (1,2), (1,3), (2,4), (3,4), (4,5), how many rows does a UNION ALL reachability query starting at node 1 return, and how many does the UNION version return?
Show answer
UNION ALL returns 6 rows (2, 3, 4, 4, 5, 5) because node 4 is reached by two paths and each copy is expanded to reach 5. UNION returns 4 rows (2, 3, 4, 5) because the second copy of 4 is dropped before it can be expanded.
Exercise
Why can you not run a UNION recursive query on SQL Server, and what is the usual substitute for cycle protection there?
Show answer
SQL Server requires UNION ALL between the anchor and recursive members. The usual substitute is to carry a path (or visited list) in the CTE and filter out nodes already on it, or to cap depth with MAXRECURSION and deduplicate in the outer query.