Common table expression (WITH)
Name a sub-result first, then use it like a table. Needs MySQL 8+ or MariaDB 10.2+.
SQL · Common table expression (WITH)Intermediate
WITH paid AS (
SELECT customer_id, SUM(total) AS spent
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
),
big AS (
SELECT * FROM paid WHERE spent >= 300
)
SELECT c.name, big.spent
FROM big
JOIN customers c ON c.id = big.customer_id;ctewithreadability