Recall & Review
beginner
What is a Recursive CTE in SQL?
A Recursive CTE (Common Table Expression) is a query that refers to itself to repeatedly process hierarchical or tree-structured data until a condition is met.
Click to reveal answer
beginner
Why use Recursive CTEs for hierarchical data?
Recursive CTEs let you easily query data with parent-child relationships, like organizational charts or file systems, by walking through levels step-by-step.Click to reveal answer
intermediate
What are the two main parts of a Recursive CTE?
1. Anchor member: The starting query that selects the root rows.<br>2. Recursive member: The query that references the CTE itself to find child rows.
Click to reveal answer
intermediate
How do you stop infinite recursion in a Recursive CTE?
By including a condition in the recursive member that eventually stops returning new rows, such as when no more child rows exist.
Click to reveal answer
intermediate
Example: What does this Recursive CTE do?<br>
WITH RECURSIVE subordinates AS ( SELECT employee_id, manager_id, 1 AS level FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.employee_id, e.manager_id, s.level + 1 FROM employees e JOIN subordinates s ON e.manager_id = s.employee_id ) SELECT * FROM subordinates;
It finds all employees in a company starting from top managers (no manager) and lists their subordinates at each level, showing the hierarchy depth.
Click to reveal answer
What keyword starts a Recursive CTE in PostgreSQL?
✗ Incorrect
Recursive CTEs always start with the keyword 'WITH RECURSIVE' in PostgreSQL.
In a Recursive CTE, what does the anchor member do?
✗ Incorrect
The anchor member selects the initial rows from which recursion begins.
How do you prevent infinite loops in Recursive CTEs?
✗ Incorrect
A termination condition stops recursion when no new rows are found.
Which of these is a common use case for Recursive CTEs?
✗ Incorrect
Recursive CTEs are ideal for hierarchical data such as trees or organizational structures.
What does the UNION ALL do in a Recursive CTE?
✗ Incorrect
UNION ALL combines the initial anchor rows with the recursive results at each step.
Explain how a Recursive CTE works to retrieve hierarchical data.
Think about starting from the top and walking down the tree.
You got /4 concepts.
Describe a real-life example where Recursive CTEs can be used and why.
Imagine a company with managers and employees.
You got /4 concepts.