Before continuing: This entry is part of the GROUP BY guide. If you are new to the topic, start with GROUP BY.
HAVING example
Cancelled orders are excluded first. The remaining orders are then grouped by customer, and only customers whose total is above 300 are kept.
SELECT c.name,
ROUND(SUM(p.total), 2) AS total_purchased,
COUNT(*) AS orders
FROM customers AS c
JOIN orders AS p
ON p.customer_id = c.id
WHERE p.status <> 'cancelled'
GROUP BY c.id, c.name
HAVING SUM(p.total) > 300
ORDER BY total_purchased DESC, c.name;WHERE keeps cancelled amounts out of the sum. HAVING checks each customer's total once it has been calculated.
Check the result with small data
Sales are added up by category first, and then those sums are filtered.
WITH sales(category, amount) AS (
VALUES ('Books', 8), ('Books', 7), ('Audio', 6)
)
SELECT category, SUM(amount) AS total
FROM sales GROUP BY category
HAVING SUM(amount) > 10;| category | total |
|---|---|
| Books | 15 |
Books exceeds 10 overall; Audio does not. WHERE cannot directly replace HAVING SUM(...) because it runs before grouping.
Check your understanding: Which category would appear if the threshold were 5?
Show answer
Books and Audio: Books adds up to 15 and Audio to 6, and both exceed 5.
What changes from case to case
An aggregate query without GROUP BY treats the whole input as a single group. HAVING decides whether that summary row is returned: if the condition is not met, the result is empty. This is handy for raising an alert when the whole set crosses a threshold.
In the StoreSQL database there are 18 orders. The query below returns one row because the set contains at least 15.
SELECT COUNT(*) AS orders,
ROUND(SUM(total), 2) AS amount
FROM orders
HAVING COUNT(*) >= 15;| orders | amount |
|---|---|
| 18 | 3931,9 |
If you raise the threshold to 20, you get zero rows, not a row with orders = 0. There are still 18 orders: HAVING discards the summary. If you always need the count back, remove that condition and decide how to interpret the value in the application.
Do not select an individual column such as status alongside that overall aggregate: without grouping by it, there is no single status that represents every row. To get an alert per status, use GROUP BY status and evaluate each group separately.
Common mix-ups with HAVING
Using WHERE with an aggregate function
WHERE COUNT(*) > 3 tries to evaluate the count before the groups exist. The aggregate condition belongs in HAVING.
Filtering rows too late
If you only want to add up shipped orders, put status = 'shipped' in WHERE. Grouping everything and trying to fix it afterwards can give a different result.
Relying on an alias in HAVING
Whether you can use a SELECT in HAVING alias varies between engines. For a portable query, repeat the aggregate expression.