Java Zero to All All questionsPractise free
Interview questions › Databases & Persistence › SQL Mastery & Joins

How do CTEs and self-joins help, and when is a recursive CTE the right tool?

Level III · MidSQL Mastery & Joins
Short answer

A common table expression (WITH ...) names a subquery to improve readability and let you reference it multiple times, and a self-join joins a table to itself to relate rows within it, like matching employees to their managers in the same table.

Explanation

A recursive CTE is the right tool for hierarchical or graph traversal such as an org chart, bill-of-materials, or category tree, walking parent-child relationships to arbitrary depth. Be aware that in some databases CTEs were historically an optimization fence (materialized), so on hot paths verify the plan rather than assuming the optimizer inlines them.

Common mistakes
  • Writing recursive CTEs without a termination condition.
  • Not knowing CTEs may or may not be materialised depending on the database.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for SQL Mastery & Joins.

Practise free

More on SQL Mastery & Joins