Skip to main content
Module 14 · Lesson 1 of 353/57 in the course~14 min
Module lessons (1/3)

Introduction to CTEs (WITH)

Lesson preview5 hands-on exercises readySQL Course · Module 14 — CTEs and Hierarchical Queries (WITH)

Factor out temporary named result sets cleanly at the top of a query.

What you'll learn in this lesson

  • Replace unreadable nested subqueries ("Spaghetti SQL") with blocks named via WITH nome_cte AS (...).
  • Recognize when the Query Planner inlines a non-recursive CTE vs when to force MATERIALIZED.
  • Use CTEs as pre-filtering and clean deduplication before the final JOIN.

Overview

Nesting SELECT inside FROM inside another WHERE quickly produces queries that are difficult to read and correct. CTEs (Common Table Expressions, WITH) flip the structure from the inside out in a linear sequence: first you declare the intermediate bricks with descriptive names, then you write the final SELECT that combines them.

Step up the stepper to see exactly where the construction of the virtual table CTE fits in with the FROM, JOIN, WHERE, and SELECT of the main query:

Sections covered in this lesson

  1. 11. Mental Model: Top-Down Readability and Modern Inlining
  2. 22. Progressive & Annotated Examples
  3. 33. Interactive Laboratory: The CTE Block in the Logic Flow
  4. 44. Diagnostic Verification (Quiz)
  5. 55. Progressive Practical Laboratory
Pro Lesson · Module 14 — CTEs and Hierarchical Queries (WITH)

Unlock "Introduction to CTEs (WITH)" and the full SQL Course curriculum

Factor out temporary named result sets cleanly at the top of a query.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in SQL Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.