Example 1
Summarize order totals per customer, then filter top spenders
The CTE totals groups and sums each customer's orders. The outer query then filters to customers whose total exceeds 200. Bob (140) is excluded. Writing this without a CTE would require a subquery in FROM or repeating the aggregation twice.
CREATE TABLE orders (id INT, customer VARCHAR(50), amount INT);
INSERT INTO
orders (id, customer, amount)
VALUES
(1, 'Alice', 100),
(2, 'Alice', 150),
(3, 'Bob', 80),
(4, 'Bob', 60),
(5, 'Carol', 300);WITH
totals AS (
SELECT
customer,
SUM(amount) AS total
FROM
orders
GROUP BY
customer
)
SELECT
customer,
total
FROM
totals
WHERE
total > 200
ORDER BY
total DESC;| customer | total |
|---|---|
| Carol | 300 |
| Alice | 250 |
Output is identical across all supported engines.