Lesson 2.3

CTEs and subqueries

A common table expression lets you name an intermediate result, so a three-stage query reads as three named steps rather than as nested subqueries you have to unpick from the…

4mIntermediate12.5k students

Overview

Naming the steps of a query

A common table expression lets you name an intermediate result, so a three-stage query reads as three named steps rather than as nested subqueries you have to unpick from the inside.

Recursive CTEs traverse hierarchies — category trees, org charts, dependency graphs — in a single statement, with a base case and a step, and a termination condition you must get right.

Modern PostgreSQL usually inlines a CTE into the surrounding query, but marking one as materialised forces evaluation once. That is occasionally the fix for a plan that recomputes an expensive step repeatedly.

In this lesson you will:

  • Name a step to make a query readable
  • Walk a hierarchy with a recursive CTE
  • Know when a CTE changes the plan

Resources

Previous Lesson
Next Lesson
CTEs and subqueries — PostgreSQL for Application Developers — Vertex