LESSON 07 / 24·2 min readFoundation

When should I use a recursive CTE or set operation?

01 Understand02 Recall03 Prepare

Understand the concept

A recursive CTE repeatedly extends an initial result to walk relationships such as a manager hierarchy. Set operations combine compatible result sets by keeping all rows, common rows or differences. They solve different needs: recursion follows links, while set operations compare or combine complete results.

Important ideas

  • Recursive CTE: walk a hierarchy, such as employee → manager.

  • UNION removes duplicate result rows; UNION ALL keeps them.

  • INTERSECT finds common rows; EXCEPT finds rows missing from the second result.

  • Recursive queries need a termination condition or cycle handling when the data can contain loops.

PAUSE & RECALL

Can you explain it without the notes?

When should I use a recursive CTE or set operation?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

A recursive CTE repeatedly extends an initial result to walk relationships such as a manager hierarchy. Set operations combine compatible result sets by keeping all rows, common rows or differences. They solve different needs: recursion follows links, while set operations compare or combine complete results.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • UNION removes duplicates, which costs work; use UNION ALL when duplicates are valid or already impossible.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: GROUP BY vs a window function?

Adapted from 05_SQL_POSTGRESQL.md · “When should I use a recursive CTE or set operation?”. Examples are study fragments; framework behavior can depend on your version.