Lesson 5: GROUP BY & HAVING
06 Jul 2026 1 min Swarnil Singhai
GROUP BY buckets rows by a shared value before aggregating; HAVING filters those aggregated groups — different from WHERE, which filters rows.
Real-time example
A retailer wants revenue per customer, but only customers who've spent over Rs 5000 total.
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 5000
ORDER BY total_spent DESC;
What's happening
WHERE filters rows before grouping; HAVING filters the resulting groups after SUM() has already been computed — that's why HAVING can reference SUM().
If your filter condition uses an aggregate function, it belongs in HAVING, not WHERE.
Advertisement