A Recursive CTE (Common Table Expression) is a query that refers to itself to repeatedly execute and build a result set step-by-step, often used to work with hierarchical or tree-structured data.
Click to reveal answer
beginner
What are the two main parts of a Recursive CTE?
1. Anchor member: The starting query that runs once. 2. Recursive member: The part that references the CTE itself to repeat and build on the results.
Click to reveal answer
intermediate
Why do Recursive CTEs need a termination condition?
To stop the recursion from running forever, a condition limits how many times the recursive part runs, usually by checking when no new rows are added.
Click to reveal answer
beginner
Give a simple real-life example where Recursive CTEs are useful.
Finding all employees under a manager in a company hierarchy, where each employee can have subordinates, and you want to list everyone below a certain manager.
Click to reveal answer
beginner
What SQL keyword is used to define a Recursive CTE?
The keyword WITH is used to start a CTE, and the RECURSIVE keyword (in some SQL dialects like PostgreSQL) indicates that the CTE is recursive.
Click to reveal answer
What does the anchor member of a Recursive CTE do?
AStarts the recursion with initial rows
BTerminates the recursion
CJoins two tables
DDeletes rows from a table
✗ Incorrect
The anchor member runs once to provide the initial rows for the recursion.
Which SQL keyword is commonly used to start a Recursive CTE?
ASELECT
BWITH
CJOIN
DINSERT
✗ Incorrect
WITH starts a CTE, including recursive ones.
Why must a Recursive CTE have a termination condition?
ATo avoid infinite loops
BTo speed up the query
CTo join tables
DTo create indexes
✗ Incorrect
Without a termination condition, recursion would continue forever.
What kind of data is Recursive CTE especially good for?
AFlat lists
BImages
CHierarchical or tree data
DRandom numbers
✗ Incorrect
Recursive CTEs are great for hierarchical data like org charts.
In PostgreSQL, which keyword must be added to WITH to make a CTE recursive?
AITERATE
BLOOP
CREPEAT
DRECURSIVE
✗ Incorrect
The RECURSIVE keyword tells PostgreSQL the CTE will call itself.
Explain how a Recursive CTE works step-by-step.
Think of climbing a ladder one step at a time until you reach the top.
You got /4 concepts.
Describe a real-world scenario where you would use a Recursive CTE.
Imagine finding all family members in a family tree.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of a Recursive CTE in SQL?
easy
A. To create temporary tables for one-time use
B. To join two unrelated tables
C. To optimize query performance by indexing
D. To repeatedly execute a query to process hierarchical or linked data
Solution
Step 1: Understand Recursive CTE definition
A Recursive CTE runs a query repeatedly, starting from an anchor and then recursively processing related rows.
Step 2: Identify its main use
This is mainly used to explore hierarchical or linked data stepwise, like organizational charts or folder trees.
Final Answer:
To repeatedly execute a query to process hierarchical or linked data -> Option D
Quick Check:
Recursive CTE = repeated query for linked data [OK]
Hint: Recursive CTEs repeat queries to explore linked data [OK]
Common Mistakes:
Confusing recursive CTE with simple temporary tables
Thinking recursive CTEs optimize indexes
Assuming recursive CTEs join unrelated tables
2. Which of the following is the correct basic syntax to start a recursive CTE in SQL?
easy
A. WITH cte_name AS (SELECT ... UNION ALL SELECT ... FROM cte_name ...)
B. CREATE RECURSIVE cte_name AS SELECT ...
C. SELECT * FROM cte_name RECURSIVE
D. WITH RECURSIVE cte_name SELECT ... UNION SELECT ...
Solution
Step 1: Recall recursive CTE syntax
The standard syntax starts with WITH cte_name AS (anchor_query UNION ALL recursive_query).
Step 2: Check options for correct form
WITH cte_name AS (SELECT ... UNION ALL SELECT ... FROM cte_name ...) correctly shows the anchor and recursive parts combined with UNION ALL and references the CTE name in the recursive part.
Final Answer:
WITH cte_name AS (SELECT ... UNION ALL SELECT ... FROM cte_name ...) -> Option A
Quick Check:
Recursive CTE syntax = WITH + UNION ALL + self-reference [OK]
Hint: Recursive CTE uses WITH + UNION ALL + self-reference [OK]
Common Mistakes:
Using CREATE instead of WITH
Omitting UNION ALL
Not referencing the CTE name recursively
3. Given the table Employees(id, manager_id) and this recursive CTE:
WITH RECURSIVE EmpCTE AS (
SELECT id, manager_id FROM Employees WHERE id = 1
UNION ALL
SELECT e.id, e.manager_id FROM Employees e JOIN EmpCTE c ON e.manager_id = c.id
)
SELECT id FROM EmpCTE ORDER BY id;
What does this query return?
medium
A. All employees who have no manager
B. All employees who report directly or indirectly to employee with id 1
C. Only the employee with id 1
D. All employees in the table
Solution
Step 1: Analyze the anchor query
The anchor selects employee with id = 1.
Step 2: Analyze the recursive part
The recursive part joins Employees where manager_id matches the id from previous results, thus finding direct reports, then their reports, and so on.
Final Answer:
All employees who report directly or indirectly to employee with id 1 -> Option B
Quick Check:
Recursive CTE finds all subordinates under id 1 [OK]
Hint: Recursive join on manager_id finds all reports [OK]
Common Mistakes:
Thinking it returns only the anchor row
Assuming it returns employees without managers
Believing it returns all employees regardless of manager
4. Identify the error in this recursive CTE:
WITH RECURSIVE Numbers AS (
SELECT 1 AS num
UNION ALL
SELECT num + 1 FROM Numbers WHERE num < 5
)
SELECT * FROM Numbers;
medium
A. Missing anchor query
B. No termination condition in recursive part
C. Recursive CTE syntax is correct and will run successfully
D. Using UNION instead of UNION ALL causes infinite loop
Solution
Step 1: Check anchor query
The anchor selects 1 AS num, which is correct.
Step 2: Check recursive part and termination
The recursive part adds 1 to num and stops when num reaches 5, so it has a termination condition.
Final Answer:
Recursive CTE syntax is correct and will run successfully -> Option C
Quick Check:
Anchor + recursive with termination = valid recursive CTE [OK]
Hint: Check for termination condition and correct UNION ALL usage [OK]
5. You want to calculate the factorial of 5 using a recursive CTE. Which query correctly computes this?
hard
A. WITH RECURSIVE Fact(n, fact) AS (
SELECT 1, 1
UNION ALL
SELECT n + 1, fact * (n + 1) FROM Fact WHERE n < 5
)
SELECT fact FROM Fact WHERE n = 5;
B. WITH Fact AS (
SELECT 1 AS n, 1 AS fact
UNION
SELECT n + 1, fact * n FROM Fact WHERE n <= 5
)
SELECT fact FROM Fact WHERE n = 5;
C. WITH RECURSIVE Fact(n, fact) AS (
SELECT 1, 1
UNION ALL
SELECT n + 1, fact * n FROM Fact WHERE n < 5
)
SELECT fact FROM Fact WHERE n = 5;
D. WITH RECURSIVE Fact(n, fact) AS (
SELECT 0, 1
UNION ALL
SELECT n + 1, fact * n FROM Fact WHERE n < 5
)
SELECT fact FROM Fact WHERE n = 5;
Solution
Step 1: Understand factorial calculation
Factorial of n is product of all integers from 1 to n. We start with n=1, fact=1.
Step 2: Check recursive step correctness
WITH RECURSIVE Fact(n, fact) AS (
SELECT 1, 1
UNION ALL
SELECT n + 1, fact * (n + 1) FROM Fact WHERE n < 5
)
SELECT fact FROM Fact WHERE n = 5; correctly increments n by 1 and multiplies fact by (n+1), matching factorial definition up to 5.
Step 3: Verify termination and final selection
It stops when n reaches 5 and selects fact at n=5, giving 120.
Final Answer:
Option A correctly computes factorial of 5 using recursive CTE -> Option A
Quick Check:
Factorial recursion: multiply by next number, stop at 5 [OK]
Hint: Multiply by n+1 each step, stop at target number [OK]
Common Mistakes:
Starting from 0 causing multiplication by zero
Using UNION instead of UNION ALL
Incorrect multiplication order in recursive step
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.