Bird
0
0

Given the table edges(source INT, target INT) with data:

medium📝 query result Q13 of 15
PostgreSQL - Common Table Expressions
Given the table edges(source INT, target INT) with data:
(1, 2), (2, 3), (3, 4), (2, 5)
What will the following query return?
WITH RECURSIVE path AS (SELECT source, target FROM edges WHERE source = 1 UNION ALL SELECT e.source, e.target FROM edges e JOIN path p ON e.source = p.target) SELECT * FROM path ORDER BY source, target;
ARows: (1,2), (2,3), (2,5), (3,4)
BRows: (1,2), (2,3), (3,4)
CRows: (1,2), (2,5)
DEmpty result
Step-by-Step Solution
Solution:
  1. Step 1: Identify the anchor and recursive parts

    The anchor selects edges where source=1: (1,2). The recursive part joins edges where source matches previous target.
  2. Step 2: Trace recursive expansion

    From (1,2), next edges with source=2 are (2,3) and (2,5). From (2,3), next edge with source=3 is (3,4). No further edges from 5 or 4.
  3. Final Answer:

    Rows: (1,2), (2,3), (2,5), (3,4) -> Option A
  4. Quick Check:

    Recursive join expands all reachable edges [OK]
Quick Trick: Follow edges from start node stepwise [OK]
Common Mistakes:
  • Ignoring multiple edges from same source
  • Stopping recursion too early
  • Misordering results

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes