Bird
0
0

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

medium📝 query result Q4 of 15
PostgreSQL - Common Table Expressions
Given the table edges(source INT, target INT) with data:
(1, 2), (2, 3), (3, 4)
What will be the output of this query?
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;
A(1,2), (2,3), (3,4)
B(1,2), (2,3)
C(1,2)
D(2,3), (3,4)
Step-by-Step Solution
Solution:
  1. Step 1: Understand anchor member

    The anchor selects edges starting at source=1, so (1,2) is included first.
  2. Step 2: Recursive member joins edges where source matches previous target

    From (1,2), next edge with source=2 is (2,3), then from (2,3) next is (3,4).
  3. Final Answer:

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

    Recursive join finds all connected edges from source=1 [OK]
Quick Trick: Recursive CTE follows edges step-by-step from anchor [OK]
Common Mistakes:
  • Stopping after first recursion
  • Ignoring recursive join condition
  • Misreading anchor member

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes