Sub topic 6
Reading grouped results in Apex with AggregateResult
This chapter assumes you can write basic SOQL with GROUP BY and aggregate functions, and that you know Apex variables, loops, and casting. It covers how Apex hands the rows of a grouped query back to you and how to read them without runtime errors.
What a grouped query returns
A normal SOQL query returns a list of a specific sObject type, such as List<Account>. A query that uses GROUP BY or an aggregate function such as SUM(Amount) does not return real records. It returns AggregateResult objects, one per group. An AggregateResult has no Id, no typed fields, and no DML support. It is a bag of named values.
You can loop over the query directly, as in this example from the plan:
for (AggregateResult ar : [
SELECT StageName, COUNT(Id) cnt, SUM(Amount) total
FROM Opportunity
GROUP BY StageName
]) {
String stage = (String) ar.get('StageName');
Integer cnt = (Integer) ar.get('cnt');
Decimal total = (Decimal) ar.get('total');
System.debug(stage + ': ' + cnt + ' opportunities, total ' + total);
}You can also assign the result to a list: List<AggregateResult> rows = [SELECT ...];. Each row holds one value per selected expression.
Reading values with get
The only way to read a value is ar.get(name). It takes a string and returns Object, so you must cast the result yourself. The name is one of two things:
- For a grouped field such as
StageName, the field name. - For an aggregate expression, the alias you gave it, such as
cntortotal.
The name is case-insensitive. If it matches nothing in the query, Apex throws a System.SObjectException at runtime. The compiler cannot catch the mistake, so a typo in a string only shows up when that line runs.
Aliases and the exprN fallback
If you leave an aggregate expression without an alias, Salesforce names it for you. The names are expr0, expr1, and so on, numbered in the order the unaliased aggregates appear in the SELECT list. Grouped fields do not use up numbers.
List<AggregateResult> rows = [
SELECT StageName, COUNT(Id), SUM(Amount)
FROM Opportunity
GROUP BY StageName
];
for (AggregateResult ar : rows) {
Object count = ar.get('expr0');
Object total = ar.get('expr1');
System.debug(ar.get('StageName') + ' -> ' + count + ', ' + total);
}This works, but it is fragile. If someone adds AVG(Amount) before SUM(Amount), your expr1 now reads a different column and the cast may fail or, worse, succeed with the wrong meaning. Alias every aggregate you read in Apex.
The numbering also depends on which expressions are unaliased. If you alias COUNT(Id) but not SUM(Amount), the sum becomes expr0.
Types you get back
get returns whatever type the platform chose. These are the types to cast to.
| Selected expression | Value returned by get |
|---|---|
| `COUNT(Id)`, `COUNT_DISTINCT(field)` | `Integer` |
| `SUM`, `AVG` on currency or number fields | `Decimal` |
| `SUM`, `AVG` on Double fields | `Double` |
| `MIN`, `MAX` | The type of the field (`Date`, `Datetime`, `String`, `Decimal`, and so on) |
| A grouped field | The type of the field |
| `CALENDAR_YEAR(CloseDate)` and other date functions | `Integer` |
A wrong cast throws a System.TypeException. For example, casting a Double result to Decimal fails. When you are not sure what a field produces, read into Object first and check it with instanceof, or normalize through a helper like this one:
public class AggregateReader {
public static Decimal toDecimal(Object value) {
if (value == null) {
return null;
}
if (value instanceof Decimal) {
return (Decimal) value;
}
if (value instanceof Integer) {
Decimal d = (Integer) value;
return d;
}
if (value instanceof Long) {
Decimal d = (Long) value;
return d;
}
if (value instanceof Double) {
return Decimal.valueOf((Double) value);
}
throw new TypeException('Unsupported numeric type: ' + value);
}
}Null values are normal
Two kinds of null appear in grouped results, and both are easy to miss.
- A null group key. If some records have no
LeadSource, SOQL returns a group whoseLeadSourceisnull. It is a real row, andar.get('LeadSource')returnsnullfor it. If you use that value as aMapkey or call.toLowerCase()on it, you must handle the null case. - A null aggregate.
SUM,AVG,MIN, andMAXignore null field values. If every value in a group is null, the result isnull, not0. Arithmetic on it throws aSystem.NullPointerException.
for (AggregateResult ar : [
SELECT LeadSource src, COUNT(Id) cnt
FROM Lead
GROUP BY LeadSource
]) {
String src = (String) ar.get('src');
String label = (src == null) ? '(no source)' : src;
System.debug(label + ': ' + (Integer) ar.get('cnt'));
}Note that COUNT(Id) is never null. It returns 0 or more. COUNT(field) counts only non-null values of that field, which can differ from COUNT(Id).
Turning rows into a Map
Most real code does not process rows in a loop and forget them. It converts them into a structure that other code can look up. A Map keyed by the group value is the usual choice.
Map<String, Decimal> totalByStage = new Map<String, Decimal>();
Map<String, Integer> countByStage = new Map<String, Integer>();
for (AggregateResult ar : [
SELECT StageName stage, COUNT(Id) cnt, SUM(Amount) total
FROM Opportunity
GROUP BY StageName
]) {
String stage = (String) ar.get('stage');
countByStage.put(stage, (Integer) ar.get('cnt'));
Decimal total = (Decimal) ar.get('total');
totalByStage.put(stage, total == null ? 0 : total);
}
System.debug(totalByStage);
System.debug(countByStage);Two details are worth noting. First, StageName stage aliases a grouped field. This is allowed, and from then on you read it with get('stage'), not get('StageName'). Second, the code replaces a null total with 0 before storing it, so later arithmetic is safe.
Aliasing grouped fields from related objects and date functions
Grouped values that are not plain fields are the most common place where the lookup name is unclear. A date function or a related field such as Account.Industry does not map cleanly to a single field name. Give it an alias and read it by that alias.
for (AggregateResult ar : [
SELECT CALENDAR_YEAR(CloseDate) yr, Account.Industry ind, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY CALENDAR_YEAR(CloseDate), Account.Industry
]) {
Integer yr = (Integer) ar.get('yr');
String ind = (String) ar.get('ind');
Decimal total = (Decimal) ar.get('total');
System.debug(yr + ' / ' + ind + ': ' + total);
}An alias cannot repeat another alias or field name in the same query, and it should not be a SOQL reserved word. Short, descriptive names such as cnt, total, and yr are safe.
Limits and constraints to remember
AggregateResultrows cannot be passed toinsert,update, ordelete. If you want to create records from totals, copy the values into real sObjects first.Database.getQueryLocatordoes not accept aggregate queries, so aDatabase.Batchableclass cannot use one instart. Return anIterablefromstartinstead, or run the aggregate query in a normal method.- A plain
SELECT COUNT() FROM Accountwith no field and noGROUP BYdoes not returnAggregateResultrows. Assigned to anInteger, it returns the count directly. UseCOUNT(Id)with an alias when you want a row you can read withget. - Aggregate queries still count against the SOQL query limit per transaction. A query inside a loop that runs once per record is a problem even when each query returns a single row.
Common mistakes
- Reading an unaliased result by guessing its name. Use aliases so the name does not depend on the position in the
SELECTlist. - Casting to the wrong type.
COUNTisInteger, notDecimal. Currency sums areDecimal. Check the table above. - Skipping the null checks. Both the group key and the aggregate value may be
null. - Expecting sObject behavior. There is no
ar.Id, noar.Name, and no dot notation for fields. Everything goes throughget.
Exercise
A developer writes [SELECT StageName, COUNT(Id), SUM(Amount) FROM Opportunity GROUP BY StageName] and wants the sum in Apex. What name does she pass to ar.get, what type does she cast to, and what should she do to make the code safer?
Show answer
The sum is the second unaliased aggregate, so its name is 'expr1' (COUNT(Id) is 'expr0'). Amount is a currency field, so she casts to Decimal. To make the code safer she should alias the aggregates, for example COUNT(Id) cnt and SUM(Amount) total, and read them with ar.get('cnt') and ar.get('total'). Reading by alias keeps the code correct if the SELECT list is reordered. She should also handle a null total before doing arithmetic on it.
Exercise
Why does ar.get('LeadSource') sometimes return null in a GROUP BY LeadSource query, and how would you store that group in a Map<String, Integer>?
Show answer
Leads with no LeadSource value form their own group, and its group key is null. It is a real row, not an error. Replace the null with a label before using it as a key, for example String key = (src == null) ? '(no source)' : src; then countBySource.put(key, (Integer) ar.get('cnt'));