Bird
0
0

How can you modify a recursive CTE to prevent infinite loops caused by cycles in hierarchical data?

hard📝 Application Q9 of 15
PostgreSQL - Common Table Expressions
How can you modify a recursive CTE to prevent infinite loops caused by cycles in hierarchical data?
ARemove the anchor member to stop recursion
BReplace UNION ALL with UNION to remove duplicates
CAdd a path tracking column and filter out rows already visited in recursion
DUse a LIMIT clause inside the recursive part
Step-by-Step Solution
Solution:
  1. Step 1: Understand cycle prevention

    Tracking visited nodes (e.g., with a path array) helps detect and skip cycles during recursion.
  2. Step 2: Evaluate other options

    Replacing UNION ALL with UNION does not prevent cycles, removing anchor stops recursion, LIMIT only limits rows but not cycles.
  3. Final Answer:

    Add a path tracking column and filter out rows already visited in recursion -> Option C
  4. Quick Check:

    Track visited nodes to avoid cycles [OK]
Quick Trick: Track visited nodes to stop cycles in recursion [OK]
Common Mistakes:
  • Thinking UNION removes cycles
  • Removing anchor member stops recursion entirely
  • Using LIMIT does not prevent cycles

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes