Common Table Expressions (CTEs)

Lesson 14 of 20

Give a subquery a name and reuse it — watch a WITH clause build a temporary result the main query can read.

The big picture

Name it, then use it

A CTE is a subquery with a name. The WITH clause computes it once up front, and the main query reads the result like a real table.

WITH declares

WITH name AS ( SELECT ... ) attaches a name to a query before the main SELECT starts.

Runs first

The CTE query executes and its rows are held as a temporary result for this one statement.

Reads like a table

FROM high_paid works exactly like FROM any_table — the rows come from the temp result.

Chains nicely

Several CTEs can be declared, and later ones may read earlier ones — step by step.