Sub topic 10
Grouping by Fields on Related Objects
This chapter assumes you know basic SOQL (SELECT, FROM, WHERE, ORDER BY), the idea of GROUP BY from earlier chapters, and how relationship fields such as Account.Industry work. Here you will group child records by a field on a parent record.
Why group by a related field
Often the value you want to group on lives on another object. An Opportunity has no Industry field, but its Account does. SOQL lets you traverse the lookup or master-detail relationship in the GROUP BY clause with dot notation. You get one row per distinct parent value without a second query or any Apex-side grouping.
SELECT Account.Industry, COUNT(Id) oppCount
FROM Opportunity
GROUP BY Account.IndustryThis returns one row for each distinct Account.Industry value. The oppCount column holds the number of opportunities in that group.
How the relationship path works
The path starts at the object in the FROM clause and follows relationship names, not object names. For standard lookups the relationship name is the field name without Id, such as Account for AccountId. For custom lookups it is the field name ending in __r, such as Project__r.Region__c.
Every selected non-aggregate field must also appear in GROUP BY. If you select Account.Industry, you must group by Account.Industry.
Reading related-field results in Apex
In Apex, the result is an AggregateResult. For a related field with no alias, the key is the field path as written. This is the approach that works for the query above:
for (AggregateResult ar : [
SELECT Account.Industry, COUNT(Id) oppCount
FROM Opportunity
GROUP BY Account.Industry
]) {
String industry = (String) ar.get('Industry');
Integer cnt = (Integer) ar.get('oppCount');
System.debug(industry + ': ' + cnt);
}Note that the key is Industry, not Account.Industry. Grouped fields are returned under the last segment of the path. Aliases are only available on aggregate expressions, so you cannot rename the grouped field itself.
Null parents and filtering
Opportunities with no Account have a null AccountId. They are not dropped. They form their own group, and the related field value is null. Accounts with a blank Industry fall into the same null group. In Apex, check for null before using the string.
You can restrict rows with WHERE, using the same relationship path:
SELECT Account.Industry, COUNT(Id) oppCount
FROM Opportunity
WHERE Account.Industry != null
GROUP BY Account.IndustryCommon errors
| Symptom | Cause | Fix |
|---|---|---|
| "Field must be grouped or aggregated" | Related field is selected but not in GROUP BY | Add the same path to GROUP BY |
| `ar.get('Account.Industry')` returns an exception or null | Key is the last path segment | Use `ar.get('Industry')` |
| Unexpected null group | Parent missing or field blank | Filter with WHERE or handle `null` |
| Invalid relationship name | Used the object name or omitted `__r` | Use the relationship name |
Exercise
You run SELECT Account.Type, COUNT(Id) total FROM Opportunity GROUP BY Account.Type in Apex. What key do you pass to ar.get to read the account type, and what key reads the count?
Show answer
Use ar.get('Type') for the account type, because grouped fields are keyed by the last segment of the path. Use ar.get('total') for the count, because it has the alias total.