HAVING
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.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in