Sub topic 4
Grouping results with GROUP BY
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT). It also assumes you know Salesforce objects and field types, and basic Apex syntax such as loops and casting.
The previous chapters covered aggregate functions such as COUNT and SUM. Used alone, they collapse the whole result into one row. GROUP BY splits the matching records into buckets first, so each aggregate function returns one value per bucket.
What GROUP BY does
GROUP BY takes the records that match the query and puts records with the same value in the grouped field into one group. The query then returns one row per group.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSourceIf your leads come from Web, Phone Inquiry, and Partner Referral, you get three rows, one per source. Each row holds the source value and the number of leads with that value. The word leadCount after COUNT(Id) is an alias. A later chapter covers aliases in detail. For now, treat it as a name for the aggregate column.
The diagram shows where grouping fits in query processing.
WHERE runs before grouping and removes individual records. HAVING runs after grouping and removes whole groups. Both get their own chapters. Here you only need to know that grouping happens in the middle.
The rule for selected fields
Every field in the SELECT list must be one of two things:
- A field named in the
GROUP BYclause. - A field wrapped in an aggregate function such as
COUNT,SUM,AVG,MIN, orMAX.
The rule exists because a group holds many records. A single row for the group can show the value they share, which is the grouped field. It can also show a summary of the values that differ, which is an aggregate. It cannot show "the" Status of a group of leads that have different statuses.
SELECT LeadSource, Status, COUNT(Id)
FROM Lead
GROUP BY LeadSourceThis query fails. Status is neither grouped nor aggregated, and Salesforce returns an error saying the field must be grouped or aggregated. You have two ways to fix it:
- Add
Statusto theGROUP BYclause if you want one row per source and status pair. - Remove
Status, or wrap it in an aggregate such asMAX(Status)if a summary of it is useful.
Grouping by more than one field
List several fields, separated by commas, to group by combinations of their values.
SELECT StageName, LeadSource, COUNT(Id) oppCount, SUM(Amount) totalAmount
FROM Opportunity
GROUP BY StageName, LeadSourceYou get one row for each distinct pair of StageName and LeadSource that exists in the data. If no opportunity is in the Prospecting stage with the source Partner, no row appears for that pair. Zero-count groups are never returned, because a group exists only when at least one record falls into it.
The number of rows grows with the number of distinct combinations. Two fields with 10 values each can produce up to 100 rows. Keep this in mind when you choose fields.
| Query shape | Rows returned |
|---|---|
| Aggregate function, no GROUP BY | One row for the whole result |
| GROUP BY one field | One row per distinct value of that field |
| GROUP BY two fields | One row per distinct pair of values that occurs |
Null values form their own group
Records with an empty value in the grouped field are not dropped. They are collected into a single group whose grouped field is null. If 40 leads have no LeadSource, one row has LeadSource set to null and a count of 40.
This matters when you read the results in Apex. The grouped value can be null, so any code that calls a method on it, such as source.toLowerCase(), must check for null first.
Nulls also affect the aggregate inside each group. COUNT(Id) counts every record in the group, because Id is never null. COUNT(Amount) counts only records whose Amount is not null. Compare these two queries:
SELECT StageName, COUNT(Id) allOpps, COUNT(Amount) oppsWithAmount
FROM Opportunity
GROUP BY StageNameFor each stage, allOpps is greater than or equal to oppsWithAmount. A gap between the two columns tells you some records have no amount.
Reading grouped results in Apex
In Apex, a query with GROUP BY returns AggregateResult objects instead of Lead or Opportunity records. You read each column by calling get with the field name or alias. The method returns an Object, so you cast it to the type you expect. A later chapter covers AggregateResult in full. This example is enough for now.
List<AggregateResult> rows = [
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource
];
for (AggregateResult ar : rows) {
String source = (String) ar.get('LeadSource');
Integer total = (Integer) ar.get('leadCount');
System.debug((source == null ? '(no source)' : source) + ': ' + total);
}The code checks source for null so the group of leads with no source prints a readable label. You can copy the loop into Anonymous Apex in a Developer Edition org or a sandbox, and it runs as shown.
Which fields can you group by
You cannot group by every field. Fields such as long text areas and multi-select picklists are not groupable. The field describe call, DescribeFieldResult.isGroupable(), tells you whether a field can be used. Most text, picklist, number, date, checkbox, and lookup fields can be grouped.
You can group by a lookup or master-detail field such as AccountId. The group value is the record Id of the related record. Grouping by a field on a related object, such as Account.Industry, is covered in its own chapter.
You also cannot use GROUP BY with SELECT FIELDS(...), and you cannot combine it with FOR UPDATE. Aggregate queries return summary rows, not records, so features that depend on real records do not apply.
Choosing the grouping fields
Pick grouping fields that have a modest number of distinct values. Good candidates are picklists, record types, owners, and date parts. Poor candidates are fields that are unique or nearly unique, such as Name, Email, or Id. Grouping by those gives one row per record, which has the cost of an aggregate query with none of the benefit.
If you only need totals, such as a count of all leads, skip GROUP BY and use the aggregate function alone. If you need to inspect individual records, use a normal query.
Common mistakes
- Selecting an ungrouped field. The query fails with an error that the field must be grouped or aggregated. Add the field to
GROUP BYor aggregate it. - Treating the results as sObjects. In Apex, assign grouped results to
List<AggregateResult>. Assigning them toList<Lead>fails. - Forgetting the null group. The group for empty values appears as a row with a
nullvalue. Handle it in code. - Expecting empty groups. A combination with no matching records does not appear. If a report needs a row of zero for every possible value, add the missing rows in Apex.
- Leaving aggregates unnamed. Without an alias, Salesforce names the columns
expr0,expr1, and so on, in the order they appear. This works, but it breaks easily when someone reorders theSELECTlist.
Key points
GROUP BYturns many records into one row per distinct value, or per distinct combination of values.- Every selected field must be grouped or aggregated.
- Null values form their own group.
- Only combinations that exist in the data produce rows.
- In Apex, grouped results arrive as
AggregateResultobjects, read withgetand a cast.
Exercise
A query selects Industry, Rating, and COUNT(Id) from Account and has GROUP BY Industry. It fails. Explain why, and give two corrected versions that mean different things.
Show answer
Rating is neither in the GROUP BY clause nor inside an aggregate function, and one row for an industry group cannot show a single rating when the accounts in it have different ratings. Fix 1: SELECT Industry, Rating, COUNT(Id) FROM Account GROUP BY Industry, Rating returns one row per industry and rating pair. Fix 2: SELECT Industry, COUNT(Id) FROM Account GROUP BY Industry returns one row per industry and drops the rating, which gives a count of all accounts in each industry.
Exercise
Your Apex loop over grouped Lead results throws a NullPointerException on the line source.toLowerCase(). The query is SELECT LeadSource, COUNT(Id) cnt FROM Lead GROUP BY LeadSource. What is the likely cause, and how do you fix it?
Show answer
Some leads have no LeadSource, so SOQL returns one group whose LeadSource value is null, and calling a method on null throws the exception. Check for null before using the value, for example String label = source == null ? '(no source)' : source.toLowerCase();.