Sub topic 10
Grouping by fields on related objects
This chapter assumes you can write a basic aggregate query with GROUP BY, and that you know lookup and master-detail relationships and the dot notation used to reach a parent field (for example Account.Industry).
Why group by a related field
Many reporting questions are about a record's parent, not the record itself. Examples:
- How many opportunities belong to accounts in each industry?
- How many contacts work at accounts of each type?
- What is the total case count per account owner?
The field you want to group on lives on another object. You could query the child records, loop in Apex, and build a map from the parent's value to a count. A grouped query does the same work in the database and returns only the summary rows.
SOQL lets you name a parent field directly in GROUP BY, using the same dot notation as in a normal SELECT or WHERE.
SELECT Account.Industry, COUNT(Id) oppCount
FROM Opportunity
GROUP BY Account.IndustryThe query reads every opportunity, follows its AccountId lookup to the account, reads Industry, and forms one group per distinct value. COUNT(Id) counts opportunities in each group, not accounts.
The rule: the primary object is the one in FROM
An aggregate query always starts from one object, the one in the FROM clause. Aggregate functions summarize that object's rows. Related fields only supply the grouping key.
This has a direction that matters:
- Child to parent works. From
Opportunityyou can group byAccount.Industry. FromContactyou can group byAccount.Type. These are the fields you reach by following a lookup or master-detail field upward. - Parent to child does not work. From
Accountyou can't group by a field on its opportunities. A child relationship returns many rows per parent, so there is no single value to group on.
If you want a parent-to-child summary, flip the query. To get opportunity totals per account, start from Opportunity and group by the account:
SELECT AccountId, SUM(Amount) total
FROM Opportunity
GROUP BY AccountIdCustom relationships use the __r form, for example Project__r.Region__c. Standard parent traversal can go several levels up, such as Account.Owner.Name from a contact or opportunity query. Keep it shallow: each extra level adds a join, which slows the query on large tables.
Mixing related and local fields
You can group by several fields, and they don't all need to be on the same object. Every non-aggregate field in SELECT must also appear in GROUP BY.
SELECT Account.Industry, StageName, COUNT(Id) cnt, SUM(Amount) total
FROM Opportunity
GROUP BY Account.Industry, StageName
ORDER BY Account.Industry, StageNameThis returns one row for each combination of industry and stage that exists in the data. Combinations with no opportunities don't appear.
| Account.Industry | StageName | cnt | total |
|---|---|---|---|
| Banking | Prospecting | 4 | 120000 |
| Banking | Closed Won | 7 | 410000 |
| Energy | Prospecting | 2 | 55000 |
| null | Prospecting | 3 | 30000 |
The values are illustrative. Note the last row. It is explained next.
Null parents and null values
Two different situations both produce a null group key:
- The opportunity has an account, but the account's
Industryis blank. - The opportunity has no account at all, so there is no parent to read.
SOQL puts both into the same null group. You can't tell them apart from the grouped values alone. If the distinction matters, add the lookup Id to the query or filter in WHERE:
SELECT Account.Industry, COUNT(Id) cnt
FROM Opportunity
WHERE AccountId != null
GROUP BY Account.IndustryThis drops opportunities with no account before grouping. The remaining null group then contains only accounts whose industry is blank.
Filtering on the parent
Related fields can appear in WHERE as well as in GROUP BY. The filter runs per row before grouping, as with local fields.
SELECT Account.Industry, COUNT(Id) oppCount
FROM Opportunity
WHERE Account.Type = 'Customer' AND IsClosed = false
GROUP BY Account.Industry
HAVING COUNT(Id) > 5WHERE removes opportunities before they are grouped. HAVING then removes groups whose count is 5 or fewer. HAVING can only refer to aggregate expressions or grouped fields, so the earlier rule still holds.
Reading related-field results in Apex
In Apex, aggregate results come back as AggregateResult objects, and you read each value with get. For a local field the key is the field name, such as StageName. For a related field, the key is the field name without the relationship prefix. Account.Industry is read as Industry.
Map<String, Integer> oppsByIndustry = new Map<String, Integer>();
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');
oppsByIndustry.put(industry, cnt);
}
System.debug(oppsByIndustry);A Map<String, Integer> accepts a null key, so the null group from the previous section is stored without extra handling. If you later display the map, replace null with a label such as '(No industry)'.
Always alias the aggregate expressions. Without an alias, Salesforce names the results expr0, expr1, and so on, which breaks if you reorder the SELECT list. If you are unsure what keys a query produces, run System.debug(ar) on one row and read the field names it prints.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Selecting `Account.Name` but grouping only by `Account.Industry` | Query error: the field must be grouped or aggregated | Add `Account.Name` to `GROUP BY`, or remove it from `SELECT` |
| Querying `FROM Account` and grouping by `Opportunities.StageName` | Query error: child relationships can't be grouped on | Query `FROM Opportunity` and group by `Account.Id` or an account field |
| Reading `ar.get('Account.Industry')` | Apex raises an error for an invalid field | Use `ar.get('Industry')` |
| Treating the `null` group as "no account" | Mixes missing parents and blank values | Filter with `WHERE AccountId != null` first |
| Grouping by a long text or other non-groupable field on the parent | Query error: the field can't be grouped | Group by a groupable field, such as a picklist or text field |
Design choices
A query grouped by a parent field does a join for every row it scans. On objects with millions of records, put selective filters in WHERE (an indexed date or status field, for example) so the database scans fewer rows before it joins and groups.
If the same summary is requested often, consider storing it. A roll-up summary field on a master-detail parent, or a scheduled job that writes totals to a custom object, avoids recomputing a join-and-group on every request. Use the live query when the grouping changes per request, as it does when users choose the parent field themselves.
Exercise
You want the number of contacts per account type, with accounts that have no type reported separately and contacts with no account excluded. Write the SOQL, and give the Apex key you would use to read the account type from each AggregateResult.
Show answer
SELECT Account.Type, COUNT(Id) contactCount FROM Contact WHERE AccountId != null GROUP BY Account.Type. The WHERE clause removes contacts with no account, so any null group left holds contacts whose account has a blank Type. In Apex, read the type with (String) ar.get('Type') and the count with (Integer) ar.get('contactCount').
Exercise
A developer runs SELECT Account.Industry, Account.Name, COUNT(Id) FROM Opportunity GROUP BY Account.Industry and gets an error. Explain why, and give two ways to fix the query.
Show answer
Account.Name is selected but is neither grouped nor aggregated. Fix 1: add it to the grouping, GROUP BY Account.Industry, Account.Name, which gives one row per industry and account name pair. Fix 2: remove Account.Name from SELECT so the query returns one row per industry only.