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.
1 WITH declares
WITH name AS ( SELECT ... ) attaches a name to a query before the main SELECT starts.
2 Runs first
The CTE query executes and its rows are held as a temporary result for this one statement.
3 Reads like a table
FROM high_paid works exactly like FROM any_table — the rows come from the temp result.
4 Chains nicely
Several CTEs can be declared, and later ones may read earlier ones — step by step.
Name it, then use it
WITH declares1WITH name AS ( SELECT ... ) attaches a name to a query before the main SELECT starts. Runs first2The CTE query executes and its rows are held as a temporary result for this one statement. Reads like a table3FROM high_paid works exactly like FROM any_table — the rows come from the temp result. Chains nicely4Several CTEs can be declared, and later ones may read earlier ones — step by step. 4 building blocks make up Name it, then use it
Press play: the CTE builds a small temp result first, then the main query treats it like a table.
WITH gives a subquery a name: high_paid. The main query below will read it like a table.
Memory
no variables yet — press play
Console
output appears as the program runs…
Click each stage — the CTE is built before the main query ever starts reading.
The CTE holds a filtered copy. What does COUNT(*) see?
Your predicted output — one line per console line
Hint: The CTE holds the two Sales employees, Chloe and Dev. COUNT(*) just counts the rows it received.
Click a term, then click its description to lock the pair.
5 conceptsTap a card to expand ?WITHdrops into place
?CTEdrops into place
?Materializedrops into place
?Chained CTEsdrops into place
?Scopedrops into place
01WITH names a subquery so the main query can read it like a table.
02The CTE runs first; its rows live only for that one statement.
03Chained CTEs turn a monster query into readable, testable steps.
04A CTE used twice keeps its logic in one place instead of copy-paste.
05If a query is getting hard to read, promote its parts to CTEs.