1

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?

markasoftware
  • 12,292
  • 8
  • 41
  • 69
  • https://stackoverflow.com/questions/30015842/how-sql-with-recursive-statement-interpreted?rq=1 – Nick Mar 13 '20 at 06:04

1 Answers1

2

As discussed here the input to each recursive execution is just the result of the previous level, not the cumulative result so far.

The anchor level emits 1. Running the recursive part on that produces 2. Running the recursive part on 2 produces 3, and so on.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845