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 repeatedly execute and build a result set. It is useful for tasks like traversing hierarchical or graph data.
Click to reveal answer
intermediate
How does a Recursive CTE work for graph traversal?
It starts with a base query selecting initial nodes, then repeatedly joins the CTE to the graph edges to find connected nodes until no new nodes are found.
Click to reveal answer
beginner
What are the two main parts of a Recursive CTE?
1. Anchor member: the base query that runs first.<br>2. Recursive member: the query that references the CTE itself to find connected rows.
Click to reveal answer
intermediate
Why is it important to have a termination condition in a Recursive CTE?
Without a termination condition, the recursion would run forever. The query stops when no new rows are added in the recursive step.
Click to reveal answer
intermediate
Give a simple example of a Recursive CTE to find all reachable nodes from a start node in a graph.
WITH RECURSIVE reachable_nodes AS (
SELECT id FROM nodes WHERE id = 1 -- anchor member
UNION
SELECT e.target_id FROM edges e JOIN reachable_nodes r ON e.source_id = r.id -- recursive member
) SELECT * FROM reachable_nodes;
Click to reveal answer
What does the anchor member of a Recursive CTE do?
✗ Incorrect
The anchor member defines the initial rows from which recursion begins.
In graph traversal using Recursive CTE, what does the recursive member typically do?
✗ Incorrect
The recursive member joins the CTE to edges to find nodes connected to already found nodes.
What happens if a Recursive CTE has no termination condition?
✗ Incorrect
Without termination, recursion never stops, causing infinite loops or errors.
Which keyword is used to define a Recursive CTE in PostgreSQL?
✗ Incorrect
PostgreSQL uses 'WITH RECURSIVE' to start a recursive CTE.
What kind of data is Recursive CTE especially useful for?
✗ Incorrect
Recursive CTEs are designed to handle hierarchical or graph-like data structures.
Explain how a Recursive CTE can be used to traverse a graph in SQL.
Think about starting points and how to find connected nodes repeatedly.
You got /3 concepts.
Describe the importance of the termination condition in a Recursive CTE.
What happens if recursion never stops?
You got /3 concepts.