Common Table Expressions

The WITH Clause

A CTE (Common Table Expression) gives a subquery a name at the top of the statement. It makes long queries readable, step by step, and can be referenced several times.

WITH cte_name AS (
  SELECT ...
)
SELECT ... FROM cte_name;

Example

Example

Customers whose total spending is above the average customer's spending:

WITH CustomerTotals AS (
  SELECT CustomerID, SUM(Amount) AS Total
  FROM Orders
  GROUP BY CustomerID
)
SELECT c.CustomerName, t.Total
FROM CustomerTotals t
JOIN Customers c ON c.CustomerID = t.CustomerID
WHERE t.Total > (SELECT AVG(Total) FROM CustomerTotals)
ORDER BY t.Total DESC;

Result: 3 rows

CustomerNameTotal
Blue Harbor Foods412
Cedar & Co320.75
Aarav Traders301.75

Several CTEs

Example

Separate CTEs with commas; later ones can use earlier ones:

WITH LineTotals AS (
  SELECT od.OrderID, SUM(od.Quantity * p.Price) AS ItemsTotal
  FROM OrderDetails od JOIN Products p ON p.ProductID = od.ProductID
  GROUP BY od.OrderID
),
Compared AS (
  SELECT o.OrderID, o.Amount, ROUND(l.ItemsTotal, 2) AS ItemsTotal
  FROM Orders o JOIN LineTotals l ON l.OrderID = o.OrderID
)
SELECT * FROM Compared WHERE ABS(Amount - ItemsTotal) > 50;

Result: 5 rows

OrderIDAmountItemsTotal
101245.5158.75
103412343.8
10515075
106320.75213
108198.4137.16