0
0
SQLquery~5 mins

Recursive CTE for series generation in SQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a Recursive CTE in SQL?
A Recursive CTE (Common Table Expression) is a temporary result set that references itself to perform repeated operations, often used to generate sequences or traverse hierarchical data.
Click to reveal answer
beginner
How does a Recursive CTE generate a series of numbers?
It starts with an initial value (anchor member) and repeatedly adds rows by referencing itself (recursive member) until a stopping condition is met.
Click to reveal answer
beginner
What are the two main parts of a Recursive CTE?
1. Anchor member: the starting query that runs once.<br>2. Recursive member: the query that references the CTE itself to add more rows.
Click to reveal answer
beginner
Why do we need a stopping condition in a Recursive CTE?
To prevent infinite loops by telling SQL when to stop adding new rows in the recursion.
Click to reveal answer
intermediate
Write a simple Recursive CTE to generate numbers from 1 to 5.
WITH Numbers AS ( SELECT 1 AS num UNION ALL SELECT num + 1 FROM Numbers WHERE num < 5 ) SELECT num FROM Numbers;
Click to reveal answer
What does the anchor member in a Recursive CTE do?
AStarts the recursion with initial rows
BStops the recursion
CReferences the CTE itself
DDeletes rows from the table
Which SQL keyword is used to combine the anchor and recursive members in a Recursive CTE?
AJOIN
BORDER BY
CGROUP BY
DUNION ALL
What happens if a Recursive CTE has no stopping condition?
AIt returns only the anchor member rows
BIt returns an empty result
CIt runs infinitely or until max recursion limit
DIt throws a syntax error
Which of these is a valid use case for Recursive CTEs?
ASorting a table alphabetically
BGenerating a list of dates
CUpdating multiple tables
DCreating indexes
In the example: WITH Numbers AS (SELECT 1 AS num UNION ALL SELECT num + 1 FROM Numbers WHERE num < 5), what is the last number generated?
A5
B1
C6
D4
Explain how a Recursive CTE generates a series of numbers step-by-step.
Think about how the query calls itself repeatedly.
You got /4 concepts.
    Describe why a stopping condition is important in Recursive CTEs and what might happen without it.
    Consider what happens if the recursion never ends.
    You got /3 concepts.