Sub topic 12
Adding subtotals with GROUP BY ROLLUP
A plain GROUP BY returns one row per combination of the grouped fields. It does not return the totals above those rows, such as a count per lead source or an overall count. GROUP BY ROLLUP adds those subtotal rows and a grand total row to the same result.
This chapter assumes you can write a basic GROUP BY query with aliased aggregates, and that you can read AggregateResult rows in Apex.
What ROLLUP does
ROLLUP takes an ordered list of grouping fields. It returns the normal grouped rows, and it also returns extra rows that aggregate away the fields from right to left. For each extra row, the aggregated-away fields are null.
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
GROUP BY ROLLUP(LeadSource, Rating)Suppose the org has these leads:
| LeadSource | Rating | Leads |
|---|---|---|
| Web | Hot | 10 |
| Web | Cold | 6 |
| Phone Inquiry | Hot | 4 |
| Phone Inquiry | Cold | 5 |
The query returns seven rows.
| LeadSource | Rating | cnt | Kind of row |
|---|---|---|---|
| Web | Hot | 10 | Detail |
| Web | Cold | 6 | Detail |
| Web | null | 16 | Subtotal for Web |
| Phone Inquiry | Hot | 4 | Detail |
| Phone Inquiry | Cold | 5 | Detail |
| Phone Inquiry | null | 9 | Subtotal for Phone Inquiry |
| null | null | 25 | Grand total |
Each subtotal row is the aggregate of the detail rows above it. The grand total row has null in every grouped field and aggregates the whole filtered record set.
Field order decides which subtotals you get
ROLLUP removes fields from the right. ROLLUP(LeadSource, Rating) gives subtotals per LeadSource. Reversing the order gives subtotals per Rating:
SELECT Rating, LeadSource, COUNT(Id) cnt
FROM Lead
GROUP BY ROLLUP(Rating, LeadSource)The detail rows are the same in both queries. The subtotal rows differ. Put the field you want subtotals for on the left, and the field you want broken down inside each subtotal on the right.
With three fields, ROLLUP(a, b, c) returns four levels:
- Rows grouped by
a, b, c. - Subtotal rows grouped by
a, b, wherecisnull. - Subtotal rows grouped by
a, wherebandcarenull. - One grand total row.
SOQL accepts up to three fields in a ROLLUP list. For n fields, the result has n + 1 levels. A rough row count is the number of distinct detail combinations, plus the distinct prefixes at each higher level, plus one.
ROLLUP versus running separate queries
Without ROLLUP, you would run three queries to get the same information:
- One grouped by both fields.
- One grouped by
LeadSourceonly. - One with no
GROUP BY.
ROLLUP does it in one query. That saves SOQL queries against the limit of 100 per synchronous transaction. It also keeps all the numbers consistent, because they come from one snapshot of the data.
The result is not free. All levels come back in a single list, and you have to tell the row types apart yourself.
Filters, aliases, and aggregates still apply
WHERE runs before grouping, so it limits which records feed every level, including the grand total. HAVING runs on each group after aggregation. You can use both with ROLLUP.
SELECT LeadSource, Rating, COUNT(Id) cnt, MAX(CreatedDate) newest
FROM Lead
WHERE IsConverted = false
GROUP BY ROLLUP(LeadSource, Rating)Here the grand total counts only unconverted leads, and newest is the latest creation date at each level. Alias every aggregate, as you do in ordinary grouped queries. Without an alias, Apex sees the name expr0, expr1, and so on.
HAVING applies to every row, subtotals included. A condition such as HAVING COUNT(Id) > 5 can remove a detail row and keep its subtotal. The subtotals then include records that are no longer visible in the result. Check that this is what you want before using it.
Reading rolled-up rows in Apex
AggregateResult returns null for a rolled-up field. This Apex labels each row:
for (AggregateResult ar : [
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
GROUP BY ROLLUP(LeadSource, Rating)
]) {
String src = (String) ar.get('LeadSource');
String rating = (String) ar.get('Rating');
Integer cnt = (Integer) ar.get('cnt');
String kind;
if (src == null && rating == null) {
kind = 'grand total';
} else if (rating == null) {
kind = 'subtotal for ' + src;
} else {
kind = 'detail';
}
System.debug(kind + ': ' + cnt);
}This works only while the data contains no real null values in those fields.
The null ambiguity
LeadSource and Rating are optional fields, so many orgs have leads where they are empty. In a plain GROUP BY, those leads form their own group with a null key. In a ROLLUP, that real group looks the same as a subtotal row.
Take the group of leads that have a LeadSource of Web and no Rating:
| LeadSource | Rating | cnt | Meaning |
|---|---|---|---|
| Web | null | 3 | Web leads with no rating (a real group) |
| Web | null | 19 | Subtotal for all Web leads |
Both rows have the same key values. The Apex above would mislabel the first one as a subtotal. A related problem appears at the top: leads with no source and no rating produce a detail row with two null keys, which looks like the grand total.
The GROUPING function exists for this. It returns 1 when a field was aggregated away in that row and 0 when it is a real value, and a later chapter covers it. Until then, treat null in a rolled-up result as ambiguous on any field that can be empty.
A cheaper workaround is to filter out the empty values with WHERE, for example WHERE Rating != null. This removes the real nulls but also removes those records from every total, so the numbers stop describing your whole data set.
Ordering results
Row order is not guaranteed to match the neat layout shown in the table. Use ORDER BY on the grouped fields when order matters. Even then, null sorts in a fixed position, so subtotals may not sit directly under their detail rows. If you need a particular layout, such as a report with subtotals below each block, build it in Apex. Collect the rows into a map keyed by source, then print them in the order you want.
Map<String, Integer> subtotals = new Map<String, Integer>();
Integer grandTotal = 0;
for (AggregateResult ar : [
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
WHERE LeadSource != null AND Rating != null
GROUP BY ROLLUP(LeadSource, Rating)
]) {
String src = (String) ar.get('LeadSource');
String rating = (String) ar.get('Rating');
Integer cnt = (Integer) ar.get('cnt');
if (src == null) {
grandTotal = cnt;
} else if (rating == null) {
subtotals.put(src, cnt);
}
}
System.debug('Grand total: ' + grandTotal);
System.debug('Subtotals: ' + subtotals);The WHERE clause makes the null check safe here, at the cost described above.
Limits and gotchas
- A
ROLLUPlist takes up to three fields. - You cannot combine
ROLLUPandCUBEin one query. Each takes the whole list of grouped fields. - Every returned row counts toward the Apex limit of 50,000 query rows per transaction. A
ROLLUPadds subtotal rows, so a high-cardinality field can return many more rows than the plain grouping would. - Every selected field that is not an aggregate must appear in the
ROLLUPlist. - Related fields such as
Account.Industrywork in the list, as they do in a plainGROUP BY.
Exercise
A query uses GROUP BY ROLLUP(StageName, Type) on Opportunity. The org has 4 distinct stages and 3 distinct types, and every stage appears with all 3 types. Every opportunity has both fields populated. How many rows does the query return, and which rows have a null Type?
Show answer
It returns 17 rows: 12 detail rows (4 x 3), 4 subtotal rows (one per stage), and 1 grand total row. The 4 subtotal rows and the grand total row have a null Type. The grand total row also has a null StageName.
Exercise
You change the query to GROUP BY ROLLUP(Type, StageName). What changes in the result, and what stays the same?
Show answer
The detail rows and the grand total stay the same. The subtotal rows change: there are now 3 of them, one per Type, with StageName null, instead of 4 per StageName. The row count becomes 12 + 3 + 1 = 16.