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?
✗ Incorrect
Recursive CTEs begin with the keyword 'WITH RECURSIVE' followed by the CTE name and query.
In a Recursive CTE, what does the anchor member do?
✗ Incorrect
The anchor member defines the starting rows, usually the root nodes in hierarchical data.
How does a Recursive CTE know when to stop recursion?
✗ Incorrect
Recursion stops naturally when the recursive member returns no new rows to add.
Which SQL clause is used to combine the anchor and recursive parts in a Recursive CTE?
✗ Incorrect
UNION ALL combines the anchor member and recursive member results in Recursive CTEs.
What kind of data is best suited for Recursive CTEs?
✗ Incorrect
Recursive CTEs are designed to handle hierarchical data like organizational charts or folder trees.
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.