HAVING filters groups. It goes after GROUP BY and keeps only the groups that meet a condition on an aggregate function: customers with more than one order, products that add up to more than $1,000, and so on.
SELECT columns, aggregateFunction(column)
FROM table
WHERE conditionOnRows
GROUP BY columns
HAVING conditionOnGroups;
HAVING vs WHERE
Both filter, but at different moments of the query:
| Clause | What it filters | When it runs | Allows aggregate functions? |
|---|---|---|---|
WHERE |
Rows | Before grouping | No |
HAVING |
Groups | After grouping | Yes |
That is why this query fails: when WHERE is evaluated the groups don’t exist yet, so COUNT(*) means nothing.
WHERE clause. SQL Server reports it with a message like: An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list.Basic example
The right way to get the customers with more than one order is to move the condition to HAVING:
| customerId | orders |
|---|---|
| 2 | 2 |
| 4 | 2 |
Only Mavin (customerId = 2) and Helen (customerId = 4) have placed more than one order.
HAVING with SUM
Any aggregate function works. Here, the customers whose total spending is over $3,000, joined to Customers to show their names:
| name | lastName | totalSpent |
|---|---|---|
| Helen | Ward | 4999.00 |
| Peter | Davis | 4304.25 |
| Mavin | Pettitt | 3199.78 |
WHERE and HAVING in the same query
They are usually combined: WHERE drops rows before grouping and HAVING drops groups afterwards. This query counts, per product description, how many orders were placed from July 2022 onwards, and keeps only the descriptions with at least two:
| productDescription | orders | units |
|---|---|---|
| Alexa Speaker | 2 | 100 |
The order in which the engine processes a query makes this easier to follow:
FROMandJOIN: which tables are involved.WHERE: which rows stay.GROUP BY: how they are grouped.HAVING: which groups stay.SELECT: which columns are returned.ORDER BY: in what order.
WHERE even if it would also work in HAVING: the engine discards the rows before grouping and does less work.Common mistakes
- Using a
SELECTalias inHAVING.HAVING orders > 1works in some engines, such as MySQL, but not in SQL Server, becauseHAVINGis evaluated beforeSELECT. Repeat the expression:HAVING COUNT(*) > 1. - Forgetting
GROUP BY. Without it the whole table is a single group, andHAVINGreturns one row or none. - Filtering on a column that isn’t grouped. Only
GROUP BYcolumns or aggregate functions can appear inHAVING.
Practice
Change the examples above to answer these questions:
- Which customers have bought more than 50 units in total? (Hint:
SUM(productQuantity).) - Which product descriptions have an average price above $400?
- What happens if you change
>= 2to>= 1in the last example?