capypad
0 day streak
sql / intermediate
Snippet

Common Table Expressions (CTEs)

A CTE is a temporary result set that you can reference within another statement. It improves readability by breaking down complex queries into logical blocks.

snippet.sql
sql
1
2
3
4
5
6
7
8
WITH RegionSales AS (
SELECT region, SUM(amount) AS total
FROM sales
GROUP BY region
)
SELECT *
FROM RegionSales
WHERE total > 1000;
Breakdown
1
WITH RegionSales AS (
Starts the CTE definition with a descriptive name.
2
SELECT region, SUM(amount) AS total FROM sales GROUP BY region
The internal query that generates the temporary result set.
3
SELECT * FROM RegionSales WHERE total > 1000;
The main query that uses the temporary result set defined above.