SQL WITH: common table expressions (CTEs)
WITH gives a query a name. Long queries become a list of short, readable steps.
SQL skills · Subqueries and CTEs
What you will learn
A CTE works like a temporary table that exists only while the query runs.
It is the cleanest way to filter on a window function or reuse an intermediate result.
The basics
WITH gives a query a name, so a long query becomes a list of short steps. The named query is called a common table expression, or CTE.
WITH totals AS (
SELECT region, SUM(amount) AS total
FROM invoices
GROUP BY region
)
SELECT region, total
FROM totals
WHERE total > (SELECT AVG(total) FROM totals)A CTE lives only while its query runs. Several CTEs are separated by commas: WITH a AS (...), b AS (...) SELECT ...
Worked examples
Example 1
Regions whose total is above the average regional total.
WITH totals AS (
SELECT region, SUM(amount) AS total
FROM invoices
GROUP BY region
)
SELECT region, total
FROM totals
WHERE total > (SELECT AVG(total) FROM totals)Name the step once, use it twice.
Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.
Try a taskCommon mistakes
- Putting WITH in the middle of the query. It goes first.
- Forgetting the comma between two CTEs.
- Expecting the CTE to exist after the query ends.
Where you will use it at work
- Analyst: build a funnel step by step.
- Finance: totals per customer, then compare with targets.
- Product: active users per month, then month over month change.
Questions people ask
CTE or subquery?
A CTE reads top to bottom and can be reused. A subquery is fine for one small step.
Can a CTE use another CTE?
Yes, a later CTE can select from an earlier one.
Do all databases support WITH?
Yes: SQL Server, Oracle, PostgreSQL, MySQL 8, SQLite and Snowflake.
Ready to write it yourself?
Practice WITH: named steps (CTEs)