Naming an Intermediate Query with WITH
A common table expression can name an intermediate result for later use in a query, making its role and granularity visible.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace two logical stages
First compute total sales per region, then filter the named result for regions above 100. The intermediate rows each describe one region. See grouping.
Check the optimizer's rules when performance matters
A named stage is useful for reasoning even when the database optimizes execution across it. Inspect the actual plan if cost is important. Reading execution plans identifies what ran.[1]
Give an intermediate result a useful row grain
A report can compute one total per region in a common table expression and then select high totals. Naming the intermediate result makes its grouping visible without creating a permanent table. See grouping by region.
WITH reads(region, amount) AS (VALUES ('east',3), ('east',8), ('west',2)),
totals AS (SELECT region, SUM(amount) AS amount FROM reads GROUP BY region)
SELECT region, amount FROM totals WHERE amount > 10;
-- Expected: east, 11.
Check optimizer behavior when performance matters
Some uses of common table expressions can be inlined, while others can be evaluated separately according to engine and query rules. Use a query plan to test performance, independently of confirming the output.