0% found this document useful (0 votes)
4 views7 pages

Recursive Cte Questions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

Recursive Cte Questions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Recursive CTE

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.​

2.​ Recursive Query → Calls itself to fetch related data.​

3.​ Termination Condition → Stops when no more rows are returned.

Simple Example: Generating Numbers from 1 to 5

WITH Numbers AS (

-- Anchor Query (Starting point)

SELECT 1 AS num

UNION ALL

-- Recursive Query (Keeps adding 1 to num)

SELECT num + 1 FROM Numbers WHERE num < 5

SELECT * FROM Numbers;


Breakdown:

1.​ First, 1 is selected.


2.​ Then, 1 + 1 = 2, 2 + 1 = 3, … up to 5.
3.​ Stops when num reaches 5.

This is like a loop in SQL without using a traditional loop.


Some questions on same:- ​

Basic Questions

1.​ Write a recursive CTE to generate numbers from 1 to 10.​

2.​ Use a recursive CTE to calculate the sum of numbers from 1 to N (e.g., N = 10).​

3.​ Create a recursive CTE to print the Fibonacci series up to 10 terms.​

Medium Questions

4.​ Given an employee table with id, name, and manager_id, write a recursive CTE to
display the hierarchy (employee → manager).​

5.​ Find all ancestors of a given employee in an organizational structure.​

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

1. Generate numbers from 1 to 10

WITH Numbers AS (

SELECT 1 AS num

UNION ALL

SELECT num + 1 FROM Numbers WHERE num < 10

SELECT * FROM Numbers;

✅ Explanation: Starts from 1 and keeps adding 1 until it reaches 10.


2. Sum of numbers from 1 to N (e.g., N = 10)

WITH SumCTE AS (

SELECT 1 AS num, 1 AS sum_val

UNION ALL

SELECT num + 1, sum_val + (num + 1) FROM SumCTE WHERE num < 10

SELECT MAX(sum_val) AS TotalSum FROM SumCTE;

✅ Explanation: Keeps adding numbers until 10 and returns the final sum.
3. Fibonacci Series (first 10 terms)
WITH Fibonacci AS (

SELECT 0 AS num1, 1 AS num2, 1 AS term

UNION ALL

SELECT num2, num1 + num2, term + 1 FROM Fibonacci WHERE term < 10

SELECT num1 FROM Fibonacci;

✅ Explanation: Uses (previous + second previous) formula until 10 terms.

Medium Questions

4. Employee Hierarchy (employee → manager)

WITH EmployeeHierarchy AS (

SELECT id, name, manager_id, 1 AS level

FROM Employee

WHERE manager_id IS NULL -- Fetch top-level managers

UNION ALL

SELECT e.id, e.name, e.manager_id, eh.level + 1

FROM Employee e

JOIN EmployeeHierarchy eh ON e.manager_id = eh.id

SELECT * FROM EmployeeHierarchy ORDER BY level;

✅ Explanation: Starts from top-level managers and recursively fetches subordinates.


5. Find all ancestors of a given employee

WITH Ancestors AS (

SELECT id, name, manager_id FROM Employee WHERE id = 10 -- Change


ID as needed

UNION ALL

SELECT e.id, e.name, e.manager_id FROM Employee e

JOIN Ancestors a ON e.id = a.manager_id

SELECT * FROM Ancestors;

✅ Explanation: Starts from the given employee and moves upward in hierarchy.
6. Retrieve full folder hierarchy

WITH FolderHierarchy AS (

SELECT folder_id, parent_folder_id FROM Folders WHERE


parent_folder_id IS NULL

UNION ALL

SELECT f.folder_id, f.parent_folder_id

FROM Folders f

JOIN FolderHierarchy fh ON f.parent_folder_id = fh.folder_id

SELECT * FROM FolderHierarchy;


✅ Explanation: Fetches folders recursively, similar to a tree traversal.

Hard Questions

7. Find depth of each node in a tree-like structure

WITH NodeDepth AS (

SELECT id, name, parent_id, 1 AS depth

FROM TreeTable WHERE parent_id IS NULL

UNION ALL

SELECT t.id, t.name, t.parent_id, nd.depth + 1

FROM TreeTable t

JOIN NodeDepth nd ON t.parent_id = nd.id

SELECT * FROM NodeDepth;

✅ Explanation: Starts from root nodes and increments depth for child nodes.
8. Flatten JSON-like hierarchy in a table

WITH FlattenedHierarchy AS (

SELECT id, parent_id, name, CAST(name AS VARCHAR(MAX)) AS


full_path

FROM HierarchyTable WHERE parent_id IS NULL

UNION ALL

SELECT h.id, h.parent_id, h.name, CONCAT(fh.full_path, ' > ',


h.name)
FROM HierarchyTable h

JOIN FlattenedHierarchy fh ON h.parent_id = fh.id

SELECT * FROM FlattenedHierarchy;

✅ Explanation: Constructs a breadcrumb-style path for hierarchical records.


9. Find all paths in a graph (source → destination)

WITH RecursiveGraph AS (

SELECT source, destination, CAST(source AS VARCHAR(MAX)) AS path

FROM Graph WHERE source = 'A' -- Change source node

UNION ALL

SELECT g.source, g.destination, CONCAT(rg.path, ' -> ',


g.destination)

FROM Graph g

JOIN RecursiveGraph rg ON g.source = rg.destination

SELECT * FROM RecursiveGraph;

✅ Explanation: Finds all possible paths in a graph starting from node 'A'.

You might also like