Subqueries and CTEs
Common table expressions
Name a query result for one following statement.
Lesson 42 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Name a query result for one following statement.
Run the example
sql
WITH RegionCounts AS (
SELECT Region, COUNT(*) AS CustomerCount
FROM dbo.Customers GROUP BY Region
)
SELECT Region, CustomerCount
FROM RegionCounts
WHERE CustomerCount >= 5
ORDER BY Region;Read it step by step
- The CTE groups customers and names the intermediate result RegionCounts.
- The following SELECT filters the grouped counts.
- The CTE lasts for this one statement; it is not a stored table.
Check the result
| Region | CustomerCount |
|---|---|
| Midlands | 5 |
| North | 6 |
| South | 7 |
The filter applies to the CTE result, after grouping.
Practice
Use a CTE to count customers per City, then keep cities with at least three.
Check your answer and expected result
Reveal answer
sql
WITH CityCounts AS (
SELECT City, COUNT(*) AS CustomerCount
FROM dbo.Customers GROUP BY City
)
SELECT City, CustomerCount
FROM CityCounts
WHERE CustomerCount >= 3
ORDER BY City;| City | CustomerCount |
|---|---|
| Birmingham | 3 |
| London | 5 |
The CTE separates grouping from the filter over grouped rows.
Your progress
Reveal the check answer or reach the end to complete this lesson.