Sub topic 11
Aggregating across relationships with GROUP BY
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT) and read parent fields from a child query with dot notation, such as Account.Name on a Contact. It also assumes you have read short Apex snippets.
Relationship queries return records. An aggregate query returns summaries instead, such as how many contacts each account has. You can group by a parent field to get these summaries.
Grouping child records by a parent field
Start from the child object and put the parent field in both the SELECT list and the GROUP BY clause:
SELECT Account.Name, COUNT(Id)
FROM Contact
GROUP BY Account.NameSOQL collects the contacts into one group per distinct account name. It then returns one row per group with the name and the number of contacts. Each row is an AggregateResult, not a Contact. The query uses child-to-parent direction because it begins at Contact and walks up to Account.
The diagram shows how the rows collapse.
Group by the ID, not the name
Account names are not unique. Two different accounts called "Acme" fall into one group when you group by Account.Name. Group by the ID and select the name beside it:
SELECT AccountId, Account.Name, COUNT(Id) contactCount
FROM Contact
GROUP BY AccountId, Account.NameEvery field in the SELECT list must be either an aggregate function or listed in GROUP BY. The word contactCount after COUNT(Id) is an alias. It gives the result a name you can read in Apex.
Contacts with no account form their own group, where AccountId is null. Add WHERE AccountId != null if you don't want that group.
Filtering with WHERE and HAVING
WHERE filters records before they are grouped. HAVING filters the groups afterward, and it can test an aggregate value. You can combine both, and you can use parent fields in either:
SELECT AccountId, Account.Name, COUNT(Id) contactCount
FROM Contact
WHERE Account.Industry = 'Technology'
GROUP BY AccountId, Account.Name
HAVING COUNT(Id) > 3
ORDER BY COUNT(Id) DESCThis query keeps only contacts whose account is in the Technology industry. It groups them by account and drops accounts with three contacts or fewer. It lists the biggest groups first.
Reading the results in Apex
An aggregate query returns List<AggregateResult>. Read each value with get() and the alias or field name. Values come back as Object, so cast them.
List<AggregateResult> rows = [
SELECT AccountId, Account.Name acctName, COUNT(Id) contactCount
FROM Contact
WHERE AccountId != null
GROUP BY AccountId, Account.Name
HAVING COUNT(Id) > 1
];
for (AggregateResult ar : rows) {
Id accountId = (Id) ar.get('AccountId');
String name = (String) ar.get('acctName');
Integer total = (Integer) ar.get('contactCount');
System.debug(name + ' (' + accountId + '): ' + total);
}Aliasing the parent field (Account.Name acctName) gives you a simple key for get(). Without an alias, aggregate expressions get generated names such as expr0, which are easy to mix up.
Aggregates and subqueries
You can also aggregate in the other direction, by starting at the parent and counting children. The parent-to-child subquery does not do this, because a subquery in the SELECT list returns child records, not counts. To count children per parent, use the child-to-parent grouping shown above. To list the parents that have children at all, use a semi-join from the earlier chapter.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Grouping by a name instead of an ID | Different parents merge into one row | Group by the ID field |
| Selecting a field not in GROUP BY | The query is rejected | Add it to GROUP BY or aggregate it |
| Reading a result as an sObject | Cast error | Use `AggregateResult` and `get()` |
| Forgetting the null group | A row with a null parent appears | Filter with `WHERE AccountId != null` |
| Using WHERE on an aggregate value | The query is rejected | Use HAVING |
Exercise
Write a SOQL query on the custom object Task_c that counts tasks for each project, using the lookup relationship name Projectr. Return the project ID, the project name, and the count aliased as taskCount. Include only projects whose Status_c is 'Active' and that have at least 5 tasks.
Show answer
SELECT Project_c, Projectr.Name, COUNT(Id) taskCount FROM Taskc WHERE Projectr.Statusc = 'Active' GROUP BY Projectc, Project_r.Name HAVING COUNT(Id) >= 5