GROUP BY with HAVING

WHERE filters rows before they are grouped; HAVING filters the groups afterwards.

SQL · GROUP BY with HAVINGIntermediate
-- Customers who spent more than 1000 in 2026
SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent
FROM orders
WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01'
GROUP BY customer_id
HAVING SUM(total) > 1000
ORDER BY spent DESC;
group byhavingaggregate