Recursive CTE helps you repeat a query step by step until you get all related results. It is like following a chain of links one by one.
Recursive CTE concept in SQL
WITH RECURSIVE cte_name (column_list) AS ( -- Anchor member: starting query SELECT initial_columns FROM table_name WHERE condition UNION ALL -- Recursive member: refers to cte_name SELECT next_columns FROM table_name JOIN cte_name ON join_condition WHERE recursive_condition ) SELECT * FROM cte_name;
The first SELECT is the starting point (anchor).
The second SELECT repeats using results from the first, building step by step.
WITH RECURSIVE numbers(n) AS ( SELECT 1 UNION ALL SELECT n + 1 FROM numbers WHERE n < 5 ) SELECT * FROM numbers;
WITH RECURSIVE empty_cte(n) AS ( SELECT 1 WHERE false UNION ALL SELECT n + 1 FROM empty_cte WHERE n < 3 ) SELECT * FROM empty_cte;
WITH RECURSIVE single_node(n) AS ( SELECT 10 UNION ALL SELECT n + 1 FROM single_node WHERE n < 10 ) SELECT * FROM single_node;
This query finds the chain of employees managed by employee 1, showing each level down.
WITH RECURSIVE employee_hierarchy(employee_id, manager_id, level) AS ( -- Anchor: start with employee 1 SELECT employee_id, manager_id, 1 AS level FROM employees WHERE employee_id = 1 UNION ALL -- Recursive: find employee managed by current employee SELECT e.employee_id, e.manager_id, eh.level + 1 FROM employees e JOIN employee_hierarchy eh ON e.manager_id = eh.employee_id ) SELECT * FROM employee_hierarchy ORDER BY level;
Recursive CTEs run until no new rows are added, so be careful to avoid infinite loops.
Time complexity depends on how many levels or rows the recursion goes through.
Common mistake: forgetting the anchor query or the stopping condition causes infinite recursion.
Use recursive CTEs when you need to explore hierarchical or linked data step by step.
Recursive CTEs let you repeat queries stepwise to explore linked data.
They have an anchor (start) and recursive part (repeat).
Useful for hierarchies, chains, and stepwise calculations.
Practice
Recursive CTE in SQL?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 DQuick Check:
Recursive CTE = repeated query for linked data [OK]
- Confusing recursive CTE with simple temporary tables
- Thinking recursive CTEs optimize indexes
- Assuming recursive CTEs join unrelated tables
Solution
Step 1: Recall recursive CTE syntax
The standard syntax starts withWITH 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 withUNION ALLand references the CTE name in the recursive part.Final Answer:
WITH cte_name AS (SELECT ... UNION ALL SELECT ... FROM cte_name ...) -> Option AQuick Check:
Recursive CTE syntax = WITH + UNION ALL + self-reference [OK]
- Using CREATE instead of WITH
- Omitting UNION ALL
- Not referencing the CTE name recursively
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?
Solution
Step 1: Analyze the anchor query
The anchor selects employee withid = 1.Step 2: Analyze the recursive part
The recursive part joins Employees wheremanager_idmatches theidfrom 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 BQuick Check:
Recursive CTE finds all subordinates under id 1 [OK]
- Thinking it returns only the anchor row
- Assuming it returns employees without managers
- Believing it returns all employees regardless of manager
WITH RECURSIVE Numbers AS ( SELECT 1 AS num UNION ALL SELECT num + 1 FROM Numbers WHERE num < 5 ) SELECT * FROM Numbers;
Solution
Step 1: Check anchor query
The anchor selects1 AS num, which is correct.Step 2: Check recursive part and termination
The recursive part adds 1 tonumand stops whennumreaches 5, so it has a termination condition.Final Answer:
Recursive CTE syntax is correct and will run successfully -> Option CQuick Check:
Anchor + recursive with termination = valid recursive CTE [OK]
- Confusing UNION and UNION ALL effects
- Missing termination condition causing infinite recursion
- Assuming anchor query is missing
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 AQuick Check:
Factorial recursion: multiply by next number, stop at 5 [OK]
- Starting from 0 causing multiplication by zero
- Using UNION instead of UNION ALL
- Incorrect multiplication order in recursive step
Ready to prove it?
Pass the test and this pattern moves unknown
