WITH common_table_expression
defines named subqueries usable in the next statement (SELECT, INSERT, UPDATE, DELETE, MERGE)
What changes
- Input
- the CTE query's sources
- Output or change
- named temporary rowset scoped to one statement
Syntax at a glance
[ WITH <common_table_expression> [ , ...n ] ]
Work example
A query needs a readable name for an intermediate result used by its next statement.
Run the sample as one statement. Add a semicolon before WITH when an earlier statement shares the batch.
Check your work WITH common_table_expression. Totals is visible to the following SELECT only. A later statement cannot reuse that CTE name.
Practice SQL
Open in SQL Flow;WITH Totals AS
(
SELECT Region, SUM(Amount) AS Total
FROM (VALUES (N'North', 10), (N'North', 15), (N'South', 8)) AS Sales(Region, Amount)
GROUP BY Region
)
SELECT Region, Total
FROM Totals
ORDER BY Total DESC;
Open Microsoft Learn for full syntax, permissions, and details for your version.