Sub topic 9
Aggregate functions and GROUP BY
This chapter assumes you can write inline SOQL with a WHERE clause and read query results into lists. It shows how to summarize records in the database instead of looping over them in Apex.
Why aggregate in the query
Counting or summing records in an Apex loop forces you to retrieve every row first. That uses heap memory and counts against the limit on rows returned by SOQL queries. An aggregate query does the work in the database and returns only the summary rows.
The common aggregate functions are:
| Function | Result |
|---|---|
| `COUNT()` | Number of matching rows, returned as an `Integer` |
| `COUNT(field)` | Number of rows where the field is not null |
| `COUNT_DISTINCT(field)` | Number of unique non-null values |
| `SUM(field)` | Total of a numeric field |
| `AVG(field)` | Average of a numeric field |
| `MIN(field)` / `MAX(field)` | Lowest and highest value |
Grouping with GROUP BY
GROUP BY collects rows that share a value into one result row. Every field in the SELECT list must be either an aggregate function or a field named in GROUP BY. Give each aggregate an alias so you can read it back by name.
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 query returns a List<AggregateResult>. Each element is one group. You read values with get(), passing either the field name or the alias, and you cast the result to the type you expect.
WHERE versus HAVING
Both clauses filter, but they act at different stages.
WHEREfilters individual records before they are grouped.HAVINGfilters groups after aggregation, so it can use aggregate functions.
In the example above, WHERE Industry != null removes accounts with no industry. HAVING COUNT(Id) > 1 then keeps only industries that have more than one account.
Common errors
- Casting the wrong type.
COUNT(Id)returns anInteger, butSUMon a currency field returns aDecimal. A wrong cast throws aTypeExceptionat runtime. - Missing alias. Without an alias, Apex names the column
expr0,expr1, and so on. Those names work but are easy to mix up when you reorder the query. - Selecting an ungrouped field. Adding
Nameto the SELECT list without grouping by it fails with a query error. - Expecting a list from
COUNT(). A bareSELECT COUNT() FROM Accountassigns to anInteger, not to aList<AggregateResult>.
Integer total = [SELECT COUNT() FROM Account WHERE Industry = 'Energy'];
System.debug('Energy accounts: ' + total);Aggregate queries still count as one SOQL query toward the governor limit. Rows that are scanned but summarized into groups also count toward the total rows retrieved, so keep the WHERE clause selective.
Exercise
An aggregate query selects Industry, COUNT(Id) total and AVG(AnnualRevenue) avgRev grouped by Industry. You only want industries whose average revenue is above 5,000,000. Should this condition go in WHERE or HAVING, and how do you read total from each result row?
Show answer
Put it in HAVING, as HAVING AVG(AnnualRevenue) > 5000000, because it filters on an aggregate value computed after grouping. WHERE cannot use aggregate functions. Read the count with (Integer) ar.get('total') on each AggregateResult.