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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.