Sub topic 8
Filtering Groups with HAVING
This chapter assumes you can write SOQL with WHERE, ORDER BY, and LIMIT, and that you have already used GROUP BY with aggregate functions such as COUNT and SUM.
Why WHERE is not enough
WHERE tests individual records. It runs before any grouping, so it cannot see a group total. If you want only the groups whose total or count meets a condition, you need HAVING. It runs after the groups are built and tests the aggregate value of each group.
A worked example
This query finds accounts that have more than 100000 in open opportunities:
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > 100000The query runs in three steps:
WHERE IsClosed = falsediscards closed opportunities.GROUP BY AccountIdcollects the remaining rows into one group per account.HAVING SUM(Amount) > 100000drops every group whose total is 100000 or less.
The clause order is fixed: WHERE, then GROUP BY, then HAVING, then ORDER BY and LIMIT.
What HAVING can test
A HAVING condition can compare an aggregate function to a value. You can combine conditions with AND, OR, and NOT:
SELECT AccountId, COUNT(Id) oppCount, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING COUNT(Id) > 3 AND SUM(Amount) > 100000A common use is finding duplicates. This query returns each email address that appears on more than one contact:
SELECT Email, COUNT(Id) dupCount
FROM Contact
WHERE Email != null
GROUP BY Email
HAVING COUNT(Id) > 1You can also use a field from the GROUP BY list in HAVING. When a condition does not involve an aggregate, though, WHERE is usually the better place for it, because it removes rows before grouping.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `WHERE SUM(Amount) > 100000` | Query error, because aggregate functions are not allowed in `WHERE` | Move the condition to `HAVING` |
| `HAVING total > 100000` using the alias | Query error, because `HAVING` expects the expression, not the alias | Write `HAVING SUM(Amount) > 100000` |
| `HAVING` on a plain field that is not grouped | Query error, because the field is neither grouped nor aggregated | Add the field to `GROUP BY`, or use `WHERE` |
| Expecting `HAVING` to filter before totals are computed | Totals include rows you meant to exclude | Add a `WHERE` condition for those rows |
The last row is the subtle one. HAVING never changes what goes into a total. It only decides whether a finished group is returned. To exclude closed opportunities from the sum, you must filter them in WHERE.
Using it in Apex
Filtered groups arrive in Apex as AggregateResult rows. Because HAVING has already removed the small groups, your loop only sees the ones you care about:
for (AggregateResult ar : [
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > 100000
]) {
Id accId = (Id) ar.get('AccountId');
Decimal total = (Decimal) ar.get('total');
System.debug(accId + ' has open pipeline of ' + total);
}Exercise
You want contacts' email addresses that appear on at least two records, but only counting contacts where Email is not blank. Which clause holds the Email != null test, and which holds the COUNT(Id) >= 2 test?
Show answer
Email != null belongs in WHERE, because it tests individual rows before grouping. COUNT(Id) >= 2 belongs in HAVING, because it tests the size of each finished group. The full query is: SELECT Email, COUNT(Id) c FROM Contact WHERE Email != null GROUP BY Email HAVING COUNT(Id) >= 2