Sub topic 8
Filtering groups with HAVING
This chapter covers the HAVING clause in SOQL. It assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT), and that you know GROUP BY, aggregate functions such as COUNT and SUM, and field aliases from the earlier chapters.
What HAVING does
WHERE filters individual records before they are grouped. HAVING filters the groups after they have been built and aggregated. You use it when the condition depends on an aggregate value, such as "only accounts whose open opportunities total more than 100,000".
You cannot put an aggregate function in a WHERE clause. This query fails:
SELECT AccountId, SUM(Amount) total
FROM Opportunity
GROUP BY AccountId
WHERE SUM(Amount) > 100000It fails for two reasons. The clause order is wrong, and WHERE cannot evaluate an aggregate. The correct form uses HAVING.
Basic syntax
The clause order is fixed:
SELECTFROMWHERE(optional)GROUP BYHAVING(optional)ORDER BY(optional)LIMIT(optional)
Here is a first example. It lists lead sources that produced more than 50 leads:
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource
HAVING COUNT(Id) > 50SOQL evaluates COUNT(Id) for each LeadSource group and discards any group where the result is 50 or less.
WHERE and HAVING together
Most useful aggregate queries use both clauses. WHERE narrows the records, and HAVING narrows the resulting groups.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > 100000The processing order is:
- Select the opportunities where
IsClosed = false. - Group them by
AccountId. - Compute
SUM(Amount)for each group. - Keep only the groups whose sum is greater than 100000.
This order affects both results and performance. A condition on a plain field belongs in WHERE, because it removes records before any grouping work happens. Put a condition in HAVING only when it needs an aggregate or when it is on a grouped field and you have a specific reason.
Same condition, different meaning
Moving a condition between clauses can change the answer. Compare these two queries:
SELECT StageName, COUNT(Id) cnt
FROM Opportunity
WHERE Amount > 10000
GROUP BY StageNameSELECT StageName, COUNT(Id) cnt
FROM Opportunity
GROUP BY StageName
HAVING SUM(Amount) > 10000The first counts only opportunities larger than 10000 in each stage. The second counts all opportunities in each stage, but returns only the stages whose total amount exceeds 10000. The first filters rows, and the second filters groups.
What can appear in HAVING
A HAVING condition can use:
- Aggregate functions:
COUNT(),COUNT(field),COUNT_DISTINCT(field),SUM(),AVG(),MIN(),MAX(). - Fields that appear in the
GROUP BYclause. - Comparison operators such as
=,!=,<,>,<=,>=, plusIN,LIKEandNOT. AND,ORand parentheses to combine conditions.
The aggregate in HAVING does not have to appear in the SELECT list. This query returns only the account ID, yet it filters by a sum:
SELECT AccountId
FROM Opportunity
GROUP BY AccountId
HAVING SUM(Amount) > 100000You can also combine several conditions:
SELECT AccountId, COUNT(Id) oppCount, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY AccountId
HAVING COUNT(Id) >= 3 AND SUM(Amount) > 50000This returns accounts with at least three won opportunities that together exceed 50000.
Repeat the expression, not the alias
In HAVING, you must write the aggregate expression in full. SOQL does not let you refer to a select-list alias there.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
GROUP BY AccountId
HAVING total > 100000This query is invalid. Write HAVING SUM(Amount) > 100000 instead. The alias is useful for reading the result in Apex, and it has no effect inside the filter.
Filtering on a grouped field
You can filter on a field that appears in GROUP BY:
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource
HAVING LeadSource != null AND COUNT(Id) > 10For a plain field condition like LeadSource != null, WHERE is usually better, because it removes those records before grouping:
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
WHERE LeadSource != null
GROUP BY LeadSource
HAVING COUNT(Id) > 10Both versions return the same groups, but the second does less work.
Using HAVING in Apex
A HAVING query runs in Apex like any other aggregate query. The results come back as AggregateResult rows, and you read the values with get().
for (AggregateResult ar : [
SELECT AccountId, SUM(Amount) total, COUNT(Id) cnt
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > 100000
]) {
Id accountId = (Id) ar.get('AccountId');
Decimal total = (Decimal) ar.get('total');
Integer cnt = (Integer) ar.get('cnt');
System.debug(accountId + ' has ' + cnt + ' open opportunities worth ' + total);
}Apex bind variables work in HAVING, which lets you pass the threshold in:
Decimal threshold = 100000;
List<AggregateResult> rows = [
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > :threshold
];
System.debug(rows.size() + ' accounts exceed the threshold');HAVING with ORDER BY and LIMIT
HAVING runs before ORDER BY and LIMIT. The filtered groups are sorted, and then the limit is applied to the sorted result.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > 100000
ORDER BY SUM(Amount) DESC
LIMIT 10This returns the ten largest qualifying accounts. The limit does not shrink the set of groups that HAVING considers. It only trims the final output.
Edge cases and pitfalls
Groups with null aggregate values
SUM, AVG, MIN and MAX ignore null values. If every Amount in a group is null, the aggregate for that group is null, and a comparison such as SUM(Amount) > 100000 does not match it. Such a group is dropped. If you need to keep groups with no amounts, add a condition on a count, or filter on a different aggregate.
COUNT(Id) and COUNT(field) differ
COUNT(Id) counts every record in the group, because Id is never null. COUNT(Amount) counts only records where Amount is not null. A HAVING COUNT(Amount) > 5 condition can therefore remove a group that HAVING COUNT(Id) > 5 keeps.
Selected fields must be grouped or aggregated
Every field in the SELECT list must either appear in GROUP BY or be wrapped in an aggregate function. Adding HAVING does not change this rule.
HAVING without GROUP BY
A HAVING clause is normally used with GROUP BY. Without GROUP BY, there are no groups to filter. Use WHERE for record filters, and apply a threshold in Apex if you need one on a single overall total.
Limits
Aggregate queries count toward the SOQL query limit like any other query. The records an aggregate query scans still count against limits on query rows processed, so a selective WHERE helps. A HAVING filter reduces the number of rows returned to you, but it does not reduce the scanning work. Put selective conditions in WHERE first, and use HAVING only for conditions on aggregates.
Quick comparison
| Aspect | WHERE | HAVING |
|---|---|---|
| Filters | Individual records | Groups |
| Runs | Before grouping | After grouping and aggregation |
| Can use aggregate functions | No | Yes |
| Can use select-list aliases | No | No |
| Best for | Conditions on record fields | Conditions on aggregate results |
Exercises
Exercise
You want accounts that have more than five open opportunities. Write the SOQL query, and say which clause holds the open-status condition and which holds the count condition.
Show answer
SELECT AccountId, COUNT(Id) oppCount FROM Opportunity WHERE IsClosed = false GROUP BY AccountId HAVING COUNT(Id) > 5. The open-status condition is on a record field, so it goes in WHERE. The count condition is on an aggregate, so it goes in HAVING.
Exercise
A query groups opportunities by StageName and uses HAVING total > 50000, where total is the alias for SUM(Amount). The query fails. Why, and how do you fix it?
Show answer
HAVING cannot refer to a select-list alias. Repeat the expression: HAVING SUM(Amount) > 50000.
Exercise
What is the difference between "SELECT StageName, COUNT(Id) FROM Opportunity WHERE Amount > 10000 GROUP BY StageName" and "SELECT StageName, COUNT(Id) FROM Opportunity GROUP BY StageName HAVING SUM(Amount) > 10000"?
Show answer
The first removes opportunities of 10000 or less before grouping, so each count includes only larger opportunities. The second counts every opportunity in each stage and returns only the stages whose total amount is above 10000.