Recursive Cte Questions
Recursive Cte Questions
A Recursive CTE (Common Table Expression) is a way to repeatedly execute a query until a
condition is met. It’s commonly used for hierarchical data like organizational structures or
tree-like relationships.
How It Works:
1. Anchor Query → The base case that starts the recursion.
WITH Numbers AS (
SELECT 1 AS num
UNION ALL
Breakdown:
2. Use a recursive CTE to calculate the sum of numbers from 1 to N (e.g., N = 10).
Medium Questions
4. Given an employee table with id, name, and manager_id, write a recursive CTE to
display the hierarchy (employee → manager).
6. Given a directory structure with folder_id and parent_folder_id, write a recursive
CTE to retrieve the full folder hierarchy.
Hard Questions
7. Given a tree-like structure with id, name, parent_id, find the depth of each node
using a recursive CTE.
8. Implement a recursive CTE to flatten a JSON-like hierarchy stored in a database table.
9. Given a Graph table with source and destination columns, write a recursive CTE to
find all possible paths from a given starting node.
Solutions of above questions
Basic Questions
WITH Numbers AS (
SELECT 1 AS num
UNION ALL
WITH SumCTE AS (
UNION ALL
✅ Explanation: Keeps adding numbers until 10 and returns the final sum.
3. Fibonacci Series (first 10 terms)
WITH Fibonacci AS (
UNION ALL
SELECT num2, num1 + num2, term + 1 FROM Fibonacci WHERE term < 10
Medium Questions
WITH EmployeeHierarchy AS (
FROM Employee
UNION ALL
FROM Employee e
WITH Ancestors AS (
UNION ALL
✅ Explanation: Starts from the given employee and moves upward in hierarchy.
6. Retrieve full folder hierarchy
WITH FolderHierarchy AS (
UNION ALL
FROM Folders f
Hard Questions
WITH NodeDepth AS (
UNION ALL
FROM TreeTable t
✅ Explanation: Starts from root nodes and increments depth for child nodes.
8. Flatten JSON-like hierarchy in a table
WITH FlattenedHierarchy AS (
UNION ALL
WITH RecursiveGraph AS (
UNION ALL
FROM Graph g
✅ Explanation: Finds all possible paths in a graph starting from node 'A'.