When should I use a recursive CTE or set operation?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn When should I use a recursive CTE or set operation?
Definition:
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.
Key points:
-
Recursive CTE: walk a hierarchy, such as employee → manager.
-
UNIONremoves duplicate result rows;UNION ALLkeeps them. -
INTERSECTfinds common rows;EXCEPTfinds rows missing from the second result. -
Recursive queries need a termination condition or cycle handling when the data can contain loops.
Interview point:
- UNION removes duplicates, which costs work; use UNION ALL when duplicates are valid or already impossible.
Adapted from 05_SQL_POSTGRESQL.md · “When should I use a recursive CTE or set operation?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.