0
0
PostgreSQLquery~5 mins

Recursive CTE for graph traversal in PostgreSQL - 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 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?
ADefines the starting point of recursion
BTerminates the recursion
CJoins tables without recursion
DDeletes rows from the table
In graph traversal using Recursive CTE, what does the recursive member typically do?
ASelects unrelated rows
BJoins the CTE to graph edges to find connected nodes
CDeletes visited nodes
DCreates new tables
What happens if a Recursive CTE has no termination condition?
AIt runs forever causing an error or timeout
BIt returns an empty result
CIt runs once and stops
DIt automatically optimizes
Which keyword is used to define a Recursive CTE in PostgreSQL?
AWITH LOOP
BRECURSIVE SELECT
CWITH RECURSIVE
DCTE RECURSIVE
What kind of data is Recursive CTE especially useful for?
AUnrelated random data
BFlat tables without relationships
CSingle row tables
DHierarchical or graph data
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.