Sub topic 15
Limits and common pitfalls
This chapter assumes you can write aggregate queries with GROUP BY, HAVING, ROLLUP, and CUBE, and read AggregateResult rows in Apex. Here you will learn the errors that these queries produce most often and the limits that apply to them. Each pitfall comes with a fix.
Pitfall 1: selecting a field that is neither grouped nor aggregated
Every field in the SELECT list of a grouped query must appear in GROUP BY or be wrapped in an aggregate function. Otherwise the query fails at compile time or run time. Salesforce reports an error such as field 'X' must be grouped or aggregated.
-- Invalid: Name is neither grouped nor aggregated
SELECT StageName, Name, COUNT(Id) cnt
FROM Opportunity
GROUP BY StageNameThe fix depends on what you want:
- To get one row per stage, remove
Namefrom the SELECT list. - To get one row per stage and name, add
Nameto GROUP BY. - To keep a representative value, wrap the field in MIN or MAX.
If you need the detail records and the summary together, run two queries. You can also loop over a parent query that has a child subquery. Aggregate queries cannot return detail rows.
Pitfall 2: unaliased aggregates
Without an alias, Salesforce names each aggregate column expr0, expr1, and so on, in the order the aggregate expressions appear. A grouped field keeps its own field name.
AggregateResult ar = [SELECT COUNT(Id), MAX(Amount) FROM Opportunity];
Integer opportunityCount = (Integer) ar.get('expr0');
Decimal largestAmount = (Decimal) ar.get('expr1');
System.debug(opportunityCount + ' opportunities, largest ' + largestAmount);This works, but adding or reordering a column silently shifts the names. The code then casts the wrong value or throws a TypeException. Always alias aggregates and read them by alias.
Pitfall 3: wrong or missing casts
AggregateResult.get returns Object, so you must cast every value. The type depends on the function and the field:
| Expression | Typical Apex type |
|---|---|
| `COUNT(Id)`, `COUNT_DISTINCT(field)` | `Integer` |
| `SUM`, `AVG` on a currency field | `Decimal` |
| `SUM`, `AVG` on a number or percent field | `Decimal` or `Double`, depending on the field |
| `MIN`, `MAX` | the type of the field (`Date`, `Decimal`, `String`) |
| A grouped field | the type of the field |
If you are unsure, print the runtime type with System.debug(ar.get('alias')) and check it. Casting a Decimal to Integer throws a TypeException. The values in the table also differ from the query SELECT COUNT() FROM Account. That form has no field argument and no alias. Assign it directly to an Integer:
Integer accountTotal = [SELECT COUNT() FROM Account];
System.debug(accountTotal);COUNT() returns a number instead of an AggregateResult. You cannot combine it with GROUP BY or with other aggregate expressions.
Pitfall 4: nulls
Nulls affect aggregate results in three ways:
SUM,AVG,MIN,MAX, andCOUNT(field)ignore null values.COUNT(Id)counts every row, because Id is never null.- If every value in a group is null,
SUM,MIN,MAX, andAVGreturn null, not zero. Casting null is safe, but arithmetic on it throws aNullPointerException. - Records with a null grouping field form their own group, and the key in that row is null.
Guard each value before you use it:
Map<String, Decimal> totalsByStage = new Map<String, Decimal>();
for (AggregateResult ar : [
SELECT StageName, SUM(Amount) total
FROM Opportunity
GROUP BY StageName
]) {
Decimal total = (Decimal) ar.get('total');
totalsByStage.put((String) ar.get('StageName'), total == null ? 0 : total);
}
System.debug(totalsByStage);Null groups matter most with ROLLUP and CUBE. A subtotal row also has a null in the rolled-up field, so a row with a null LeadSource could be a subtotal or a group of leads that have no source. Add GROUPING(LeadSource) to the SELECT list. It returns 1 for a subtotal row and 0 for a real group, including the null group.
Pitfall 5: filtering aggregates in WHERE
WHERE runs before grouping, so it cannot reference an aggregate result. Put row conditions in WHERE and group conditions in HAVING. HAVING must repeat the aggregate expression. It cannot use the alias.
-- Invalid: aggregate in WHERE
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE SUM(Amount) > 100000
GROUP BY AccountId
-- Valid
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > 100000Ordering follows the same rule. Write ORDER BY SUM(Amount) DESC, not ORDER BY total DESC. Move every condition you can into WHERE, because filtering rows early is cheaper than grouping them all and discarding groups afterward.
Pitfall 6: the 2,000-row assignment limit
If you assign a grouped query directly to a list, and the query returns more than 2,000 rows, Apex throws a QueryException:
// Throws if the query returns more than 2,000 groups
List<AggregateResult> rows = [
SELECT AccountId, COUNT(Id) cnt
FROM Contact
GROUP BY AccountId
];The error message is Aggregate query has too many rows for direct assignment, use FOR loop. Iterate over the query in a for loop instead. The loop retrieves rows in batches:
Integer groupCount = 0;
for (AggregateResult ar : [
SELECT AccountId, COUNT(Id) cnt
FROM Contact
GROUP BY AccountId
]) {
groupCount++;
}
System.debug(groupCount + ' groups');Governor limits
Aggregate queries share the normal limits for the transaction:
- Query count: each aggregate query counts as one SOQL query. The limit is 100 in synchronous Apex and 200 in asynchronous Apex.
- Rows retrieved: the total row limit is 50,000 per transaction. Check the current Governor Limits reference for exactly how aggregate rows are counted.
- Heap size: a list of many
AggregateResultobjects uses heap. Process rows in aforloop and keep only the values you need. - Query time: an aggregate over millions of records with a non-selective filter can time out. Filter on indexed fields such as Id, CreatedDate, or lookup fields. For very large data volumes, consider a report, a batch job, or a roll-up summary field.
Some limits apply to the GROUP BY clause itself:
- ROLLUP and CUBE accept up to three grouping fields.
- You cannot combine ROLLUP and CUBE in one query.
- Some field types cannot be grouped, such as long text areas.
- Ordering and filtering by an alias is not supported. Use the full expression.
Pitfall 7: dynamic SOQL and tests
Database.query returns List<SObject>. Cast each element to AggregateResult, because the compiler cannot infer the type:
String soql = 'SELECT LeadSource, COUNT(Id) cnt FROM Lead GROUP BY LeadSource';
for (SObject row : Database.query(soql)) {
AggregateResult ar = (AggregateResult) row;
System.debug(ar.get('LeadSource') + ': ' + ar.get('cnt'));
}You also cannot construct an AggregateResult with new in a unit test. If your logic depends on aggregate output, move the parsing into a method that takes plain values, such as a Map<String, Decimal>. Test that method directly, and cover the query itself with real test records.
A troubleshooting path
Pre-flight checklist
Before you ship a grouped query, check that:
- Every selected field is grouped or aggregated.
- Every aggregate has an alias, and the code reads it by that alias.
- Every cast matches the real return type, and null results are handled.
- Row filters are in WHERE, group filters are in HAVING, and HAVING and ORDER BY use the full expression.
- The query is consumed in a
forloop when the group count might exceed 2,000. - The WHERE clause is selective enough to finish in time on production data volumes.
Exercise
A query SELECT StageName, COUNT(Id) FROM Opportunity GROUP BY StageName runs fine, but a developer later inserts SUM(Amount) before COUNT(Id) in the SELECT list. The Apex code still reads ar.get('expr0') as an Integer. What happens, and how do you prevent it?
Show answer
expr0 now refers to SUM(Amount), which is a Decimal, so the cast to Integer throws a TypeException. Prevent it by aliasing every aggregate (COUNT(Id) cnt, SUM(Amount) total) and reading values by alias.
Exercise
A ROLLUP query on Lead grouped by LeadSource returns a row where LeadSource is null and cnt is 40. How do you tell whether it is the grand total or a group of leads with no source?
Show answer
Add GROUPING(LeadSource) grpSource to the SELECT list. It is 1 on a subtotal or grand total row and 0 on a real group, including the group of leads whose LeadSource is null.
Exercise
Why does List<AggregateResult> rows = [SELECT AccountId, COUNT(Id) cnt FROM Contact GROUP BY AccountId]; fail in an org with 5,000 accounts that have contacts, and what is the fix?
Show answer
Direct assignment of an aggregate query is limited to 2,000 rows, so it throws a QueryException. Iterate with for (AggregateResult ar : [ ... ]) instead, and keep only the values you need.