For reference, here it is:
WITH range_10 AS (
SELECT 1 AS n
UNION ALL
SELECT n+1 AS n
FROM range_10
WHERE n < 10
)
SELECT * FROM range_10;
As we all know and love, this generates a single column n
with values from one through ten. However, I am confused about why there aren't duplicate values of n
in the output. Here's my understanding of how this query is executed:
Iteration 1
range_10 begins empty
range_10 ends as:
- 1
Iteration 2
range_10 ends as:
- 1
- 2
Iteration 3
range_10 ends as:
- 1
- 2
- 2
- 3
Why? Because we SELECT
'ed n+1 for all rows of the table (there were two of them), then did a UNION ALL
, which doesn't remove duplicates. To make this more clear:
Iteration 4
- 1
- 2
- 2
- 3
- 2
- 3
- 3
- 4
Does UNION ALL
really mean UNION
in the context of recursive queries? Or am I missing something more fundamental about recursive queries?