Sub topic 4
Grouping Results with GROUP BY
This chapter assumes you know basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT) and understand Salesforce objects and field types. You should also have seen COUNT and the other aggregate functions from earlier chapters.
What GROUP BY does
An aggregate function on its own collapses every matching record into one row. GROUP BY splits the records into buckets first, then applies the function to each bucket. The query returns one row per distinct value of the grouped field.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSourceIf your leads come from Web, Phone Inquiry, and Partner Referral, you get three rows, each with a count. Leads with a blank LeadSource form their own group, and its LeadSource value is null.
How the query is processed
The database reads the matching records, sorts them into groups by the grouped field, and computes each aggregate per group.
The main rule
Every field in the SELECT list must be one of two things:
- An aggregate expression, such as
COUNT(Id)orSUM(Amount). - A field that appears in the GROUP BY clause.
This query is invalid, because Company is neither aggregated nor grouped:
SELECT LeadSource, Company, COUNT(Id)
FROM Lead
GROUP BY LeadSourceA group holds many companies, so SOQL cannot choose one to show. Remove Company, add it to the GROUP BY, or wrap it in MIN() or MAX().
Grouping by more than one field
List several fields, separated by commas. Each distinct combination of values becomes one group.
SELECT LeadSource, Rating, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource, RatingIf LeadSource has 3 values and Rating has 3 values, you can get up to 9 rows. Only combinations that exist in the data appear.
Combining several aggregates
You can compute more than one aggregate in the same query. All of them apply to the same groups.
SELECT StageName, COUNT(Id) cnt, SUM(Amount) total, AVG(Amount) average
FROM Opportunity
GROUP BY StageNameEach row reports the opportunity count, the total amount, and the average amount for one stage.
Common errors
| Error or symptom | Cause | Fix |
|---|---|---|
| Field must be grouped or aggregated | A selected field is not in GROUP BY and not inside an aggregate | Add the field to GROUP BY or wrap it in an aggregate |
| A row with a `null` group value | Some records have an empty value in the grouped field | Add `WHERE LeadSource != null` if you do not want that group |
| Fewer rows than expected | You grouped by a field with few distinct values | Group by an additional field |
| Unexpected `null` in a sum | Every record in the group had a blank value in the summed field | Handle `null` when you read the result |
Exercise
You want the number of opportunities for each combination of StageName and LeadSource. Write the query, and explain why adding the Name field to the SELECT list would make it invalid.
Show answer
SELECT StageName, LeadSource, COUNT(Id) oppCount FROM Opportunity GROUP BY StageName, LeadSource. Name is neither aggregated nor listed in GROUP BY, and each group contains many different names, so SOQL has no single value to return for it.
Exercise
A query selects LeadSource and COUNT(Id) from Lead, grouped by LeadSource, and returns 4 rows. 6,000 leads have a blank LeadSource. Does the result include them, and how would you exclude them?
Show answer
Yes. Leads with a blank LeadSource form one group with a null LeadSource value, which counts as one of the 4 rows. Exclude them with WHERE LeadSource != null before the GROUP BY.