Example 1
Find customers whose total order value exceeds 200
order_totals aggregates raw rows into per-customer sums: Alice 230, Bob 290, Carol 50. high_value reads from order_totals and keeps only customers over 200. The final SELECT reads from high_value. Chaining CTEs keeps each step named and independently readable, avoiding deeply nested subqueries.
CREATE TABLE orders (id INT, customer VARCHAR(50), amount INT);
INSERT INTO
orders (id, customer, amount)
VALUES
(1, 'Alice', 80),
(2, 'Alice', 150),
(3, 'Bob', 200),
(4, 'Carol', 50),
(5, 'Bob', 90);WITH
order_totals AS (
SELECT
customer,
SUM(amount) AS total
FROM
orders
GROUP BY
customer
),
high_value AS (
SELECT
customer,
total
FROM
order_totals
WHERE
total > 200
)
SELECT
customer,
total
FROM
high_value
ORDER BY
total DESC;| customer | total |
|---|---|
| Bob | 290 |
| Alice | 230 |
All engines return the same rows ordered by total descending: Bob (290) first, then Alice (230).