Careeroza
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
| CustomerName | Total |
|---|---|
| Blue Harbor Foods | 412 |
| Cedar & Co | 320.75 |
| Aarav Traders | 301.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
| OrderID | Amount | ItemsTotal |
|---|---|---|
| 101 | 245.5 | 158.75 |
| 103 | 412 | 343.8 |
| 105 | 150 | 75 |
| 106 | 320.75 | 213 |
| 108 | 198.4 | 137.16 |