Sub topic 15
Limits and common pitfalls
This chapter assumes you can write GROUP BY queries, add WHERE and HAVING, and read results in Apex as AggregateResult. It covers the mistakes that cause most errors and surprises with aggregate SOQL.
Query errors you will see
Most failures come from a few rules.
| Mistake | Why it fails | Fix |
|---|---|---|
| Selecting a field that is not in `GROUP BY` | Each output row represents a group, so a plain field has no single value | Add the field to `GROUP BY` or wrap it in an aggregate function |
| Aggregate function in `WHERE` | `WHERE` runs before grouping, so no aggregate values exist yet | Move the condition to `HAVING` |
| Alias in `HAVING` | `HAVING` needs the aggregate expression itself | Repeat the expression, such as `HAVING SUM(Amount) > 100000` |
| `SUM` or `AVG` on a non-numeric field | These functions need numeric or currency fields | Use `MIN` or `MAX` for text and dates |
| Grouping by an unsupported field type | Some types, such as long text areas, cannot be grouped | Group by a different field |
SELECT StageName, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY StageName
HAVING SUM(Amount) > 50000Result handling pitfalls
An aggregate query returns AggregateResult rows, not records of the object. Assigning the result to List<Opportunity> fails. Use List<AggregateResult> or a for loop over the query.
Without an alias, Salesforce names aggregate columns expr0, expr1, and so on, by position. Code that reads ar.get('expr1') breaks as soon as someone reorders the select list. Always alias aggregates and read them by that name.
get returns Object, so you must cast. A SUM over a currency field gives a Decimal. A COUNT gives an Integer. A sum or average can come back as a different numeric type than you expect, so a bad cast fails at run time with a TypeException.
Nulls need explicit handling:
- Aggregate functions ignore null values.
AVGdivides by the count of non-null values only. - Records with a null grouping field form their own group, and
getreturnsnullfor that field. SUMover a group where every value is null returnsnull, not 0.
for (AggregateResult ar : [
SELECT LeadSource, COUNT(Id) cnt
FROM Lead
GROUP BY LeadSource
]) {
String source = (String) ar.get('LeadSource');
Integer cnt = (Integer) ar.get('cnt');
System.debug((source == null ? '(no source)' : source) + ': ' + cnt);
}Subtotal rows are ambiguous
In a ROLLUP or CUBE result, a subtotal row shows null in the field that was aggregated away. A real record with an empty LeadSource also shows null. You cannot tell the two apart by the value alone. Add GROUPING(field) to the select list. It returns 1 on subtotal rows and 0 on ordinary rows. Also check the current documentation for how many fields ROLLUP and CUBE accept, because there is a cap.
Governor limits
Aggregate queries still count against Apex governor limits.
- Each query counts toward the limit of 100 synchronous SOQL queries per transaction. Do not run an aggregate query inside a loop. Run one grouped query and process the rows.
- An aggregate query can count the records it processes, not only the rows it returns, toward the 50,000 retrieved-rows limit. A
COUNTover a very large object can fail with "Too many query rows". Add selectiveWHEREfilters to reduce the work. - Grouped results can be large. Use
LIMITafterORDER BYwhen you need only the top groups.
Exercise
A developer writes SELECT AccountId, SUM(Amount) FROM Opportunity GROUP BY AccountId and then reads the total with ar.get('expr0'). Name two problems with this approach and give the fix.
Show answer
The sum has no alias, so its name depends on its position and breaks if the select list changes. The code also reads the value without casting it, and get returns Object. Add an alias, as in SUM(Amount) total, then read it with (Decimal) ar.get('total').