Sub topic 11
Aggregating across relationships with GROUP BY
Earlier chapters showed how to read related records with dot notation and subqueries. This chapter covers summarizing them: counting contacts per account, summing opportunity amounts per account, and grouping by a field on a parent record. It assumes you can write child-to-parent queries, know the difference between a field name and a relationship name, and can read basic Apex.
Why aggregates start from the child
A parent-to-child subquery returns child records. It does not return a summary of them. To get one number per parent, query the child object and group by the parent. The relationship direction is child-to-parent, and the grouping does the "parent-to-child" work.
SELECT Account.Name, COUNT(Id)
FROM Contact
GROUP BY Account.NameThis query reads every Contact, collects contacts that share the same Account.Name, and returns one row per group with the count. The parent field is reached with ordinary dot notation, the same as in a plain child-to-parent query.
The rules of an aggregate query
Aggregate queries follow a few fixed rules.
- Every field in the SELECT list must either appear in GROUP BY or be wrapped in an aggregate function.
- The aggregate functions are
COUNT(),COUNT(field),COUNT_DISTINCT(field),SUM(),AVG(),MIN(), andMAX(). - WHERE filters rows before grouping. HAVING filters groups after grouping, and it is the only place to filter on an aggregate value.
- ORDER BY can use a grouped field or an aggregate expression.
- A relationship subquery in the SELECT list returns child records, so it does not combine with grouping. Put the grouping on the child object instead.
Here is a query that uses all of these clauses together:
SELECT AccountId, SUM(Amount) total, COUNT(Id) deals
FROM Opportunity
WHERE StageName = 'Closed Won'
GROUP BY AccountId
HAVING SUM(Amount) > 100000
ORDER BY SUM(Amount) DESC
LIMIT 10total and deals are aliases. Without an alias, aggregate columns are named expr0, expr1, and so on, in the order they appear. Aliases make the result readable in Apex, so use them.
Grouping by a parent field
You can group by any parent field that your user can see, not only the lookup ID.
SELECT Account.Industry, COUNT(Id)
FROM Contact
GROUP BY Account.IndustryThis returns the number of contacts per account industry. The same works for custom relationships, where you traverse the lookup through its __r name:
SELECT Project__r.Name, COUNT(Id)
FROM Task__c
GROUP BY Project__r.NameGroup by the ID, not the name
Names are not unique. Two accounts called "Acme" would merge into one group if you group by Account.Name. When each parent must stay separate, group by the lookup field itself, such as AccountId, then fetch names in a second step. Group by a parent attribute such as Account.Industry only when you want parents with the same value to merge.
The null group
Records whose lookup is empty form their own group, and the grouped value is null. In the diagram above, the contact with no account produced a null row. If you don't want it, filter it out before grouping:
SELECT AccountId, COUNT(Id)
FROM Contact
WHERE AccountId != null
GROUP BY AccountIdReading aggregate results in Apex
An aggregate query returns AggregateResult objects, not Contact or Opportunity records. You read each column with get(), which returns Object, so you cast it.
List<AggregateResult> rows = [
SELECT AccountId, COUNT(Id) total
FROM Contact
WHERE AccountId != null
GROUP BY AccountId
HAVING COUNT(Id) > 2
];
Set<Id> accountIds = new Set<Id>();
for (AggregateResult ar : rows) {
accountIds.add((Id) ar.get('AccountId'));
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
for (AggregateResult ar : rows) {
Id accountId = (Id) ar.get('AccountId');
Integer total = (Integer) ar.get('total');
System.debug(accounts.get(accountId).Name + ': ' + total);
}The pattern is: aggregate by ID, collect the IDs in a set, run one query for the parent names, and look them up in a map. That is two queries regardless of how many groups there are, so it is safe inside governor limits.
A few typing details:
COUNT()andCOUNT(field)returnInteger.SUM()andAVG()on currency fields returnDecimal. On other numeric fields the runtime type can differ, so check it withar.get('total')in the debug log before choosing a cast.- A
SUMover a group where every value is empty returnsnull. Check fornullbefore using the value in arithmetic.
Key names for grouped parent fields
When you group by a parent field such as Account.Industry, the key for that column in AggregateResult is derived from the field and is easy to get wrong. Print the result with System.debug(ar) once and use the key shown there. Grouping by a direct field such as AccountId has no such ambiguity, which is another reason to prefer it.
Combining aggregates with other relationship features
Aggregate queries still accept the filters you learned earlier.
Filter on a parent field in WHERE:
SELECT Account.Industry, COUNT(Id)
FROM Contact
WHERE Account.Type = 'Customer'
GROUP BY Account.IndustryRestrict to parents with a semi-join:
SELECT AccountId, COUNT(Id)
FROM Opportunity
WHERE AccountId IN (SELECT AccountId FROM Contact WHERE Email != null)
GROUP BY AccountIdFinding parents with zero children
A GROUP BY query only produces groups that have at least one row. An account with no contacts will never appear in a COUNT(Id) result, so you cannot find it by looking for a count of 0 or by using HAVING COUNT(Id) = 0. Use an anti-join instead:
SELECT Id, Name
FROM Account
WHERE Id NOT IN (SELECT AccountId FROM Contact)When you need a report that lists every account with its count, including zeros, run the aggregate query, then default missing accounts to zero in Apex:
Map<Id, Integer> counts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId, COUNT(Id) total
FROM Contact
WHERE AccountId != null
GROUP BY AccountId
]) {
counts.put((Id) ar.get('AccountId'), (Integer) ar.get('total'));
}
for (Account a : [SELECT Id, Name FROM Account LIMIT 200]) {
Integer n = counts.containsKey(a.Id) ? counts.get(a.Id) : 0;
System.debug(a.Name + ': ' + n);
}Choosing between a subquery and an aggregate
Both approaches answer "what do the children of each parent look like?", but they return different things.
| Need | Approach | Result type |
|---|---|---|
| The child records themselves, nested under each parent | Parent-to-child subquery | Parent records with a child list |
| One number per parent (count, sum, average) | Aggregate query on the child, grouped by the lookup | `AggregateResult` rows |
| One number per parent attribute, such as per industry | Aggregate query on the child, grouped by a parent field | `AggregateResult` rows |
| Parents that have no children | Anti-join with `NOT IN` | Parent records |
If you only need a.Contacts.size(), a subquery works but transfers every child row. An aggregate transfers one row per group and is cheaper when the number of children is large.
Common mistakes
- Selecting an ungrouped field.
SELECT Account.Name, LastName, COUNT(Id) FROM Contact GROUP BY Account.Namefails becauseLastNameis neither grouped nor aggregated. - Filtering on an aggregate in WHERE.
WHERE COUNT(Id) > 5is invalid. Move it to HAVING. - Treating results as sObjects. Writing
Contact c = [SELECT COUNT(Id) FROM Contact GROUP BY AccountId]does not compile. Assign toList<AggregateResult>. - Forgetting the cast.
ar.get('total') + 1fails at compile time because the value is typed asObject. - Grouping by name when you mean by record. Duplicate names merge into one group.
- Expecting zeros. Empty parents never appear in a grouped result.
- Ignoring row limits. Aggregate queries are still subject to governor limits and API result limits. Add a WHERE filter and a LIMIT, and test with realistic data volumes.
Exercise
You need the total closed-won Opportunity amount for each Account, and you want the Account names in the output. Which object do you query, what do you group by, and how do you get the names in Apex?
Show answer
Query Opportunity with SUM(Amount) and group by AccountId, filtering WHERE StageName = 'Closed Won'. Collect the AccountId values from the AggregateResult rows into a Set<Id>, run one query on Account for those IDs into a Map<Id, Account>, and look up each name in the map. Grouping by ID keeps accounts with identical names separate.
Exercise
A teammate writes SELECT AccountId, COUNT(Id) FROM Contact GROUP BY AccountId HAVING COUNT(Id) = 0 to find accounts with no contacts. Why does it return nothing useful, and what should they write instead?
Show answer
GROUP BY only builds groups from existing child rows, so an account with no contacts never forms a group and a count of 0 can never occur. The query also includes a null group for contacts with no account. Use an anti-join: SELECT Id, Name FROM Account WHERE Id NOT IN (SELECT AccountId FROM Contact).
Exercise
What is wrong with this query, and how do you fix it? SELECT Account.Industry, COUNT(Id) FROM Contact WHERE COUNT(Id) > 10 GROUP BY Account.Industry
Show answer
An aggregate function cannot be used in WHERE, because WHERE filters rows before grouping. Move the condition to HAVING: SELECT Account.Industry, COUNT(Id) FROM Contact GROUP BY Account.Industry HAVING COUNT(Id) > 10.