Sub topic 9
Aggregate functions and GROUP BY
This chapter covers how to summarize records in SOQL instead of looping over them in Apex. It assumes you can write a basic inline query with a WHERE clause, read a List of sObjects, and cast values in Apex. You should also know that queries count against governor limits.
Why aggregate in the query
Suppose you need the number of accounts per industry. You could query every account and count them in a loop. That uses heap memory and CPU time, and it can hit the limit of 50,000 returned rows. An aggregate query makes the database do the counting and returns only the summary rows.
An aggregate query uses functions such as COUNT(), SUM(), AVG(), MIN(), and MAX(). A GROUP BY clause splits the matching records into groups and returns one row per group.
The aggregate functions
| Function | Returns | Notes |
|---|---|---|
| `COUNT()` | Integer | Counts all matching rows. No field argument. |
| `COUNT(field)` | Integer in an `AggregateResult` | Counts rows where the field is not null. |
| `COUNT_DISTINCT(field)` | Integer | Counts distinct non-null values. |
| `SUM(field)` | Number | Works on numeric and currency fields. |
| `AVG(field)` | Number | Averages non-null values. |
| `MIN(field)` | Same type as field | Works on numbers, dates, and text. |
| `MAX(field)` | Same type as field | Works on numbers, dates, and text. |
COUNT() with no argument is special. As an inline query assigned to an Integer, it returns the count directly.
Integer total = [SELECT COUNT() FROM Account WHERE Industry = 'Technology'];
System.debug('Technology accounts: ' + total);Every other aggregate returns AggregateResult rows, even without GROUP BY. In that case, you get a single row.
AggregateResult ar = [
SELECT SUM(AnnualRevenue) revenue, AVG(AnnualRevenue) average
FROM Account
WHERE Industry = 'Technology'
];
Decimal revenue = (Decimal) ar.get('revenue');
Decimal average = (Decimal) ar.get('average');
System.debug('Total ' + revenue + ', average ' + average);A query with only aggregate functions and no GROUP BY always returns exactly one row, so assigning it to a single AggregateResult is safe. This differs from a normal single-record query, which throws a QueryException when no row matches.
Grouping with GROUP BY
Add GROUP BY to get one row per distinct value of a field. Every non-aggregate field in the SELECT list must also appear in GROUP BY.
List<AggregateResult> results = [
SELECT Industry, COUNT(Id) total, SUM(AnnualRevenue) revenue
FROM Account
WHERE Industry != null
GROUP BY Industry
HAVING COUNT(Id) > 1
];
for (AggregateResult ar : results) {
String industry = (String) ar.get('Industry');
Integer total = (Integer) ar.get('total');
Decimal revenue = (Decimal) ar.get('revenue');
System.debug(industry + ': ' + total + ' accounts, ' + revenue);
}The words total and revenue after the functions are aliases. You pass an alias to get() to read that value. Grouped fields keep their field name as the key, so Industry is read with ar.get('Industry').
WHERE versus HAVING
WHERE filters individual records before grouping. HAVING filters groups after the aggregate values are computed. Use WHERE for conditions on fields, and HAVING for conditions on aggregate results.
List<AggregateResult> results = [
SELECT StageName, SUM(Amount) pipeline
FROM Opportunity
WHERE IsClosed = false
GROUP BY StageName
HAVING SUM(Amount) > 100000
ORDER BY SUM(Amount) DESC
];
for (AggregateResult ar : results) {
System.debug(ar.get('StageName') + ': ' + ar.get('pipeline'));
}Put as many conditions as possible in WHERE. It reduces the rows the database must group, so the query runs faster. Reserve HAVING for conditions that need an aggregate value.
Reading AggregateResult values
AggregateResult.get() returns an Object, so you must cast it. Casting to the wrong type causes a TypeException. The usual types are:
COUNT(...)andCOUNT_DISTINCT(...)cast toInteger.SUMandAVGon currency or number fields cast toDecimal.MINandMAXcast to the type of the underlying field, such asDateorString.- Grouped fields cast to the field's own type.
A common error is leaving out an alias. Without one, Salesforce names the column expr0, expr1, and so on, in the order the functions appear. That works but is hard to read and breaks silently if you reorder the query. Always give each aggregate an alias.
Grouping by a related field
You can group by a parent field with dot notation. This query counts contacts per account name.
List<AggregateResult> results = [
SELECT Account.Name accountName, COUNT(Id) contacts
FROM Contact
WHERE AccountId != null
GROUP BY Account.Name
];
for (AggregateResult ar : results) {
System.debug(ar.get('accountName') + ': ' + ar.get('contacts'));
}Here the alias accountName is the key. Group by AccountId instead of Account.Name when names might repeat. Two different accounts with the same name would otherwise merge into one group.
Dates in groups
Grouping on a raw date or datetime field produces one group per distinct value, which is rarely useful. SOQL provides date functions that bucket values first.
List<AggregateResult> results = [
SELECT CALENDAR_YEAR(CloseDate) yr, CALENDAR_MONTH(CloseDate) mo, COUNT(Id) deals
FROM Opportunity
WHERE IsWon = true
GROUP BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate)
ORDER BY CALENDAR_YEAR(CloseDate), CALENDAR_MONTH(CloseDate)
];
for (AggregateResult ar : results) {
System.debug(ar.get('yr') + '-' + ar.get('mo') + ': ' + ar.get('deals'));
}Both date functions must appear in GROUP BY because both appear in SELECT. FISCAL_YEAR and FISCAL_QUARTER work the same way and follow the org's fiscal year settings.
Subtotals with GROUP BY ROLLUP
GROUP BY ROLLUP adds subtotal and grand total rows to the result. The extra rows have null in the grouped columns they summarize.
List<AggregateResult> results = [
SELECT Industry, Type, COUNT(Id) total, GROUPING(Industry) grpIndustry
FROM Account
GROUP BY ROLLUP(Industry, Type)
];
for (AggregateResult ar : results) {
Integer isSubtotal = (Integer) ar.get('grpIndustry');
System.debug(ar.get('Industry') + ' / ' + ar.get('Type')
+ ' = ' + ar.get('total') + ' (subtotal flag: ' + isSubtotal + ')');
}The GROUPING() function returns 1 when the row is a subtotal for that field and 0 otherwise. Without it, you cannot tell a subtotal row from a real group whose value is null.
Limits and edge cases
Aggregate queries have several restrictions that surprise people.
- Row limit. The query returns at most 2,000 groups when run through the standard
querycall in some contexts. Large grouped results can fail with a limit exception. AddWHEREconditions orLIMITto keep the group count small. - Rows scanned. Each record the database scans for the aggregate counts toward the 50,000 row governor limit for the transaction, even though only a few summary rows come back. A
COUNT()over a very large object can still hit the limit. - No
OFFSET.OFFSETcannot be combined withGROUP BY. - Null values.
COUNT(field),SUM, andAVGignore nulls.COUNT(Id)counts every row, sinceIdis never null. - Unsupported fields. Long text areas and some other field types cannot be aggregated or grouped.
- No
FOR UPDATE. Aggregate queries cannot lock rows. - No fields from the record itself. You cannot select a plain field that is not in
GROUP BY. To get more detail, run a second query using the group keys.
Using aggregates in a bulk-safe way
A common need is the count of child records for many parents. Instead of one query per parent, group once and store the results in a map.
Set<Id> accountIds = new Set<Id>();
for (Account a : [SELECT Id FROM Account WHERE Industry = 'Technology']) {
accountIds.add(a.Id);
}
Map<Id, Integer> contactCounts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
]) {
contactCounts.put((Id) ar.get('AccountId'), (Integer) ar.get('total'));
}
for (Id accId : accountIds) {
Integer count = contactCounts.containsKey(accId) ? contactCounts.get(accId) : 0;
System.debug(accId + ' has ' + count + ' contacts');
}Accounts with no contacts do not appear in the grouped result, so the code supplies a default of 0 with containsKey. Forgetting this is the most frequent bug in map-based aggregate code.
Aggregates versus other options
Choose the approach that fits the need.
| Need | Best choice |
|---|---|
| A single total or count | `SELECT COUNT()` or one aggregate row |
| Summary per group | `GROUP BY` with aliases |
| Total of child records on a master-detail parent | Roll-up summary field |
| Detail rows and totals together | Two queries, or a parent-to-child subquery |
A roll-up summary field keeps the total up to date without any code, but it exists only on the master side of a master-detail relationship. Use an aggregate query when no such field exists.
Exercise
You run SELECT Industry, COUNT(Id) total FROM Account GROUP BY Industry and want only industries with more than five accounts. Which clause do you add, and how do you read the count for each row?
Show answer
Add HAVING COUNT(Id) > 5 after the GROUP BY clause, because the condition depends on an aggregate value. Read each row as an AggregateResult and use (Integer) ar.get('total') for the count and (String) ar.get('Industry') for the industry.
Exercise
A map built from GROUP BY AccountId is missing some accounts you queried. Why, and how do you handle it in code?
Show answer
Accounts that have no matching contacts produce no group, so they are absent from the result. When reading the map, check containsKey and use 0 as the default for accounts without an entry.