Sub topic 6
Reading grouped results in Apex with AggregateResult
This chapter assumes you know basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT) and basic Apex (variables, loops, casting). It also assumes you have seen GROUP BY and aggregate aliases in earlier chapters.
Why AggregateResult exists
A normal SOQL query returns SObject records such as Account or Opportunity. A grouped query returns rows that are not real records. Each row holds a group key and computed values, so Apex has no typed class for it. Apex returns each row as an AggregateResult, which is a special kind of SObject that stores values by name.
You read a value by calling get() with a field name or an alias. get() returns Object, so you cast the result to the type you expect.
A worked example
This query groups opportunities by stage. It counts them and adds up their amounts.
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);
}Three details matter here:
StageNameis a grouped field, so you read it by its field name.cntandtotalare aliases. You choose the alias in the query and use the same text inget().- Each value is cast.
COUNTgives anInteger, andSUMon a currency field gives aDecimal.
Choosing the right cast
The cast must match what the aggregate returns. A wrong cast throws a TypeException at run time.
| Expression | Typical Apex type |
|---|---|
| `COUNT(Id)`, `COUNT()` | `Integer` |
| `COUNT_DISTINCT(Industry)` | `Integer` |
| `SUM(Amount)`, `AVG(Amount)` on a currency field | `Decimal` |
| `MIN(CloseDate)`, `MAX(CloseDate)` | `Date` |
| Grouped text field | `String` |
If you are unsure, assign the value to an Object variable first and print ar.get('alias') to see what you receive.
Why aliases matter here
If you leave out an alias, Apex names the column for you: expr0, expr1, and so on, in the order the aggregates appear. Code that reads ar.get('expr1') breaks when someone adds another aggregate before it. Always alias aggregate expressions and read them by name.
AggregateResult ar = [
SELECT COUNT(Id) total FROM Account
][0];
Integer accountCount = (Integer) ar.get('total');
System.debug(accountCount);An ungrouped aggregate query still returns a list with one row. That row holds the totals for all matching records.
Null values and common errors
Aggregates can return null. SUM and AVG return null when every value in a group is null, and a grouped field is null for records that have no value. A cast to Decimal is safe with null, but arithmetic on it is not. Check before you calculate.
Decimal total = (Decimal) ar.get('total');
if (total == null) {
total = 0;
}Watch for these mistakes:
- Reading a field that was not selected.
ar.get('Name')throws anSObjectExceptionifNamewas not in the query. SelectingIddoes not help, because grouped rows have no recordId. - Using a wrong alias. Alias names are matched exactly as you wrote them in the query. A typo throws an exception at run time, not at compile time.
- Assigning the result to
List<Opportunity>. Grouped queries returnList<AggregateResult>. Use that type or iterate withAggregateResult ar. - Trying to update the rows.
AggregateResultrows do not map to records, so you cannot pass them to DML.
How the data flows
Exercise
A query selects Industry, AVG(AnnualRevenue) avgRev FROM Account GROUP BY Industry. Write the Apex lines that read Industry and avgRev from an AggregateResult named ar, and handle a null average.
Show answer
String industry = (String) ar.get('Industry'); Decimal avgRev = (Decimal) ar.get('avgRev'); if (avgRev == null) { avgRev = 0; } The alias avgRev must match the query text exactly, and the null check protects later arithmetic.
Exercise
Why is ar.get('expr0') risky when the query has no alias on COUNT(Id)?
Show answer
Apex assigns expr0, expr1, and so on by position. Adding or reordering aggregates changes the names, so the code breaks or reads the wrong value. An explicit alias avoids this.