0
0
SQLquery~5 mins

Recursive CTE for hierarchical data 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 SQL query that refers to itself to process hierarchical or tree-structured data, allowing you to retrieve parent-child relationships in a single query.
Click to reveal answer
beginner
What are the two main parts of a Recursive CTE?
1. Anchor member: The initial query that returns the root rows.<br>2. Recursive member: The query that references the CTE itself to find child rows, repeating until no more children are found.
Click to reveal answer
intermediate
Why use Recursive CTEs instead of multiple queries for hierarchical data?
Recursive CTEs simplify querying hierarchical data by using a single query to traverse all levels, improving readability and performance compared to running multiple queries or loops.
Click to reveal answer
intermediate
In a Recursive CTE, what stops the recursion from running forever?
The recursion stops when the recursive member query returns no new rows, meaning there are no more child records to process.
Click to reveal answer
advanced
Example: What does this Recursive CTE do?<br>
WITH RECURSIVE EmployeeHierarchy AS (  SELECT EmployeeID, ManagerID, 1 AS Level FROM Employees WHERE ManagerID IS NULL  UNION ALL  SELECT e.EmployeeID, e.ManagerID, eh.Level + 1 FROM Employees e JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID) SELECT * FROM EmployeeHierarchy;
This query builds a hierarchy of employees starting from top-level managers (where ManagerID is NULL) and recursively finds all employees under each manager, adding a 'Level' column to show depth in the hierarchy.
Click to reveal answer
What keyword starts a Recursive CTE in SQL?
ARECURSIVE CTE
BWITH RECURSIVE
CSELECT RECURSIVE
DSTART RECURSIVE
In a Recursive CTE, what does the anchor member do?
ADefines the base rows to start recursion
BJoins tables together
CLimits the number of recursion levels
DDeletes duplicate rows
How does a Recursive CTE know when to stop recursion?
AWhen the recursive query returns no new rows
BWhen a maximum recursion level is reached
CWhen a timeout occurs
DWhen the user cancels the query
Which SQL clause is used to combine the anchor and recursive parts in a Recursive CTE?
AORDER BY
BJOIN
CGROUP BY
DUNION ALL
What kind of data is best suited for Recursive CTEs?
AFlat tabular data without relationships
BRandom unstructured text
CHierarchical or tree-structured data
DSingle row data
Explain how a Recursive CTE works to retrieve hierarchical data.
Think about starting from the top and finding children step by step.
You got /4 concepts.
    Describe a real-life example where you would use a Recursive CTE.
    Consider any data that looks like a tree or hierarchy.
    You got /4 concepts.