SQL Interview & Case Lab
Back to Performance & Query Reading

CTE vs Subquery vs Temp Table — When to Use Each

Three patterns, three performance profiles. Most analysts pick one and use it for everything — wrong. FIND_VIDEO: search 'CTE vs subquery vs temp table performance' — recommended channel: Modern SQL. Aim for 10 min or under.

13 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Subquery to CTE Refactoring — The instructor solves a menu pricing problem using a subquery and refactors it into a basic CTE.
  2. When to Use Subqueries vs CTEs — A comparison highlights MySQL version support, code readability, and workflow strategies.
  3. Multiple CTE References and Tables — Demonstrations show referencing one CTE twice in a query and joining multiple comma-separated CTEs.
  4. CTEs vs Temporary Tables — The instructor evaluates execution frequency, dataset size, and user permissions between CTEs and temp tables.
  5. Recursive CTEs and Missing Dates — A recursive CTE generates a sequential date series that is merged with stock prices to backfill nulls.
  6. Summary and Practical Rules — A final recap summarizes decision rules for choosing between subqueries, CTEs, temp tables, and recursive CTEs.
PDF notes

Frequently asked questions

When is a subquery preferred over a CTE?

Subqueries work well for simple, one-line nested filtering where a CTE adds boilerplate, or when writing code in legacy databases lacking CTE support.

How can I persist CTE results if I lack permissions to create temporary tables?

You must use CTEs within individual queries or coordinate with data engineers to materialize the logic into permanent views.

Can a later CTE in the same WITH block reference an earlier CTE?

Yes, any CTE declared in a comma-separated list can query the results of CTEs defined before it.

How does the recursive query know when to terminate?

The WHERE clause in the recursive query acts as the exit condition, ending recursion when zero rows are returned.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.