Bird
Raised Fist0
SQLquery~10 mins

Recursive CTE for series generation in SQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Recursive CTE for series generation
Start with anchor query
↓
Recursive query references CTE
↓
Add next row to series
↓
Check termination condition
↓
Stop
↓
Final result set
The recursive CTE starts with a base row, then repeatedly adds rows by calling itself until a stop condition is met, producing a series.
Execution Sample
SQL
WITH RECURSIVE numbers AS (
  SELECT 1 AS n
  UNION ALL
  SELECT n + 1 FROM numbers WHERE n < 5
)
SELECT * FROM numbers;
This query generates numbers from 1 to 5 using a recursive CTE.
Execution Table
StepQuery PartCurrent nActionResulting Rows
1Anchor queryn=1Start series with 1[1]
2Recursive queryn=1Add n+1=2 since 1<5[1, 2]
3Recursive queryn=2Add n+1=3 since 2<5[1, 2, 3]
4Recursive queryn=3Add n+1=4 since 3<5[1, 2, 3, 4]
5Recursive queryn=4Add n+1=5 since 4<5[1, 2, 3, 4, 5]
6Recursive queryn=5Stop recursion since 5 < 5 is false[1, 2, 3, 4, 5]
💡 Recursion stops when n reaches 5 because the condition n < 5 becomes false.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
n123455
Key Moments - 3 Insights
Why does the recursion stop when n equals 5?
Because the recursive query has a condition WHERE n < 5. When n is 5, this condition is false, so no new rows are added (see execution_table row 6).
What is the role of the anchor query in the recursive CTE?
The anchor query provides the starting row(s) for the recursion. Without it, the recursive part has no base to build on (see execution_table row 1).
How does the recursive query add new rows?
It selects n + 1 from the current rows where n < 5, adding one new row each recursion step (see execution_table rows 2-5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of n after step 3?
A3
B4
C2
D5
💡 Hint
Check the 'Resulting Rows' column in execution_table row 3.
At which step does the recursion stop adding new rows?
AStep 4
BStep 5
CStep 6
DStep 3
💡 Hint
Look at the 'Action' column in execution_table row 6 for the stopping condition.
If the condition changed to WHERE n < 3, how many rows would the final result have?
A2 rows
B3 rows
C5 rows
D4 rows
💡 Hint
Refer to variable_tracker and how n increments each step until the condition fails.
Concept Snapshot
Recursive CTE syntax:
WITH RECURSIVE cte_name AS (
  anchor_query
  UNION ALL
  recursive_query_referencing_cte
)
SELECT * FROM cte_name;

- Anchor query starts the series.
- Recursive query adds rows until condition fails.
- Useful for generating sequences or hierarchical data.
Full Transcript
A recursive CTE starts with an anchor query that provides the first row(s). Then, the recursive query repeatedly references the CTE itself to add new rows. This continues until a termination condition is met, stopping recursion. For example, generating numbers 1 to 5 starts with 1, then adds 2, 3, 4, and 5 one by one. When the condition n < 5 is false at n=5, recursion stops. This method is useful for creating series or traversing hierarchical data in SQL.

Practice

(1/5)
1. What is the main purpose of using a Recursive CTE in SQL for series generation?
easy
A. To generate a sequence of numbers or dates step-by-step within a query
B. To join two tables based on a common column
C. To delete duplicate rows from a table
D. To create indexes for faster searching

Solution

  1. Step 1: Understand Recursive CTE usage

    Recursive CTEs are used to repeatedly execute a query to build results step-by-step.
  2. Step 2: Identify series generation purpose

    They are commonly used to generate sequences like numbers or dates without needing extra tables.
  3. Final Answer:

    To generate a sequence of numbers or dates step-by-step within a query -> Option A
  4. Quick Check:

    Recursive CTE = sequence generation [OK]
Hint: Recursive CTEs build sequences stepwise inside SQL [OK]
Common Mistakes:
  • Confusing recursive CTE with JOIN operations
  • Thinking recursive CTE deletes duplicates
  • Assuming recursive CTE creates indexes
2. Which of the following is the correct syntax to start a recursive CTE named numbers generating numbers from 1?
easy
A. WITH RECURSIVE numbers AS SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5
B. WITH RECURSIVE numbers AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5)
C. WITH numbers RECURSIVE AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5)
D. WITH RECURSIVE numbers (num) AS (SELECT 1 AS n UNION ALL SELECT num + 1 FROM numbers WHERE num < 5)

Solution

  1. Step 1: Check correct WITH RECURSIVE syntax

    The correct syntax starts with WITH RECURSIVE cte_name AS ( ... ).
  2. Step 2: Validate the recursive query structure

    WITH RECURSIVE numbers AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5) correctly uses SELECT 1 AS num as anchor and recursive part with UNION ALL and stopping condition.
  3. Final Answer:

    WITH RECURSIVE numbers AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5) -> Option B
  4. Quick Check:

    Correct recursive CTE syntax = WITH RECURSIVE numbers AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5) [OK]
Hint: Start recursive CTE with WITH RECURSIVE cte AS (...) [OK]
Common Mistakes:
  • Placing RECURSIVE after CTE name
  • Missing parentheses around CTE query
  • Omitting AS keyword
3. Given the query:
WITH RECURSIVE seq AS (
  SELECT 1 AS n
  UNION ALL
  SELECT n + 2 FROM seq WHERE n < 7
)
SELECT * FROM seq;

What will be the output rows?
medium
A. [1, 3, 5]
B. [1, 2, 3, 4, 5, 6, 7]
C. [1, 3, 5, 7]
D. [2, 4, 6, 8]

Solution

  1. Step 1: Analyze anchor and recursive step

    Anchor row is 1. Recursive step adds 2 each time: 1, 3, 5, 7.
  2. Step 2: Check stopping condition

    Recursion stops when n < 7 is false. Since 7 is included, sequence ends at 7.
  3. Final Answer:

    [1, 3, 5, 7] -> Option C
  4. Quick Check:

    Start=1, step=+2, stop at 7 = [1,3,5,7] [OK]
Hint: Add step value repeatedly until condition fails [OK]
Common Mistakes:
  • Assuming step is 1 instead of 2
  • Stopping before reaching 7
  • Including numbers beyond 7
4. Identify the error in this recursive CTE:
WITH RECURSIVE count_up AS (
  SELECT 1 AS num
  UNION ALL
  SELECT num + 1 FROM count_up
)
SELECT * FROM count_up WHERE num <= 3;
medium
A. Using UNION instead of UNION ALL
B. Incorrect anchor query syntax
C. Wrong column alias in SELECT statements
D. Missing stopping condition inside the recursive part causing infinite recursion

Solution

  1. Step 1: Check recursive part for stopping condition

    The recursive SELECT lacks a WHERE clause to stop recursion, causing infinite loop.
  2. Step 2: Understand WHERE clause placement

    The WHERE clause outside the CTE filters final results but does not stop recursion inside CTE.
  3. Final Answer:

    Missing stopping condition inside the recursive part causing infinite recursion -> Option D
  4. Quick Check:

    Stopping condition must be inside recursive CTE [OK]
Hint: Put stopping condition inside recursive SELECT, not outside [OK]
Common Mistakes:
  • Placing stopping condition only in final SELECT
  • Confusing UNION and UNION ALL effects
  • Incorrect alias usage
5. You want to generate a list of dates from '2024-01-01' to '2024-01-05' using a recursive CTE. Which query correctly produces this date series?
hard
A. WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT dt + INTERVAL '1 day' FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates;
B. WITH RECURSIVE dates AS (SELECT '2024-01-01' AS dt UNION ALL SELECT dt + INTERVAL 1 DAY FROM dates WHERE dt <= '2024-01-05') SELECT * FROM dates;
C. WITH RECURSIVE dates AS (SELECT '2024-01-01' AS dt UNION ALL SELECT dt + 1 FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates;
D. WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT DATE(dt, '+1 day') FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates;

Solution

  1. Step 1: Understand date addition syntax

    WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT dt + INTERVAL '1 day' FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates; uses dt + INTERVAL '1 day' which is standard SQL for adding one day to a date.
  2. Step 2: Check stopping condition and anchor

    Anchor selects the start date as DATE type. Recursive part adds one day while date is less than '2024-01-05'.
  3. Step 3: Compare other options

    WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT DATE(dt, '+1 day') FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates; uses SQLite style DATE(dt, '+1 day'), which is not standard SQL. WITH RECURSIVE dates AS (SELECT '2024-01-01' AS dt UNION ALL SELECT dt + INTERVAL 1 DAY FROM dates WHERE dt <= '2024-01-05') SELECT * FROM dates; uses incorrect WHERE condition allowing extra date. WITH RECURSIVE dates AS (SELECT '2024-01-01' AS dt UNION ALL SELECT dt + 1 FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates; adds integer to date incorrectly.
  4. Final Answer:

    WITH RECURSIVE dates AS (SELECT DATE('2024-01-01') AS dt UNION ALL SELECT dt + INTERVAL '1 day' FROM dates WHERE dt < '2024-01-05') SELECT * FROM dates; -> Option A
  5. Quick Check:

    Date + INTERVAL '1 day' is standard SQL date addition [OK]
Hint: Use INTERVAL '1 day' to add days in standard SQL [OK]
Common Mistakes:
  • Using database-specific date functions in standard SQL
  • Incorrect stopping condition allowing extra dates
  • Adding integer directly to date without INTERVAL
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard