SQL Server › Common Table Expressions (CTEs)
What is a common table expression, and why would you use one instead of a subquery?
BeginnerAnswer
A common table expression, defined using the WITH keyword, creates a temporary named result set that you can reference within a single query, making complex queries easier to read and organize compared to nesting several subqueries inside each other, especially when the same intermediate result needs to be referenced more than once.
WITH HighValueOrders AS (
SELECT CustomerId, Amount
FROM Orders
WHERE Amount > 500
)
SELECT CustomerId, COUNT(*) AS OrderCount
FROM HighValueOrders
GROUP BY CustomerId;Real-world example A sales report uses a CTE to first isolate high value orders, then groups and counts them by customer, making the overall query much easier to read than nesting the same filter logic inside a subquery.