HAVING

Basic SQL
≈ 1 min read

HAVING filters groups

WHERE filters individual rows before grouping. HAVING is applied after grouping and lets you keep only groups that satisfy an aggregate condition.

SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 5;

First, orders are grouped by customer_id, then the row count is calculated for each group, and only groups with five or more orders remain in the result.

WHERE and HAVING can work together

SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'PAID'
GROUP BY customer_id
HAVING SUM(amount) > 10000;

WHERE first keeps only paid orders. They are then grouped by customer, after which HAVING keeps customers whose total payments exceed 10000.

If a condition can be checked for an individual row before grouping, it normally belongs in WHERE. HAVING is mainly needed when the condition depends on an aggregate result or on an already formed group.