Sub topic 14
Identifying subtotal rows with GROUPING
This chapter covers the GROUPING function, which tells you whether a row in a ROLLUP or CUBE result is a detail row, a subtotal row, or the grand total. It assumes you can already write GROUP BY queries, read results as AggregateResult in Apex, and use GROUP BY ROLLUP and GROUP BY CUBE. It also assumes you know that SOQL returns subtotals as extra rows.
The problem: null means two things
ROLLUP and CUBE add subtotal rows to the result. In those rows, the field that has been aggregated away comes back as null. Consider this query:
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
GROUP BY ROLLUP(LeadSource, Rating)A row with LeadSource = null could mean either of two things:
- Some leads have no lead source, and this is the group for them.
- This is the grand total row, where
LeadSourcewas rolled up.
You can't tell which from the data alone. The same ambiguity applies to Rating. Without a way to separate the two cases, any code that labels rows or formats a report will mislabel them.
GROUPING removes the ambiguity. It looks at how the row was produced, not at the value in the field.
What GROUPING returns
GROUPING(field) takes one field that appears in the ROLLUP or CUBE list. It returns an integer for each result row:
1means the field was aggregated away in this row. The row is a subtotal or grand total across all values of the field.0means the field is a real grouping value in this row. That includes a realnullvalue stored in the data.
Here is the query from the topic plan that uses it with CUBE:
SELECT LeadSource, Rating,
GROUPING(LeadSource) grpSource,
GROUPING(Rating) grpRating,
COUNT(Id) cnt
FROM Lead
GROUP BY CUBE(LeadSource, Rating)CUBE returns a subtotal for every combination of the grouped fields. With two fields there are four kinds of rows. The table shows how to read each combination of the two GROUPING values:
| grpSource | grpRating | Row type | What `cnt` counts |
|---|---|---|---|
| 0 | 0 | Detail row | Leads with this source and this rating |
| 0 | 1 | Subtotal for one source | Leads with this source, any rating |
| 1 | 0 | Subtotal for one rating | Leads with this rating, any source |
| 1 | 1 | Grand total | All leads |
With ROLLUP(LeadSource, Rating) you get the same table without the 1, 0 row. A rollup only produces subtotals from right to left: first Rating is rolled up, then LeadSource.
A worked example with sample data
Suppose the lead data looks like this:
| LeadSource | Rating | Number of leads |
|---|---|---|
| Web | Hot | 4 |
| Web | Cold | 6 |
| Web | (blank) | 2 |
| (blank) | Hot | 3 |
A ROLLUP(LeadSource, Rating) query with both GROUPING fields returns these rows. The row order is not guaranteed unless you add ORDER BY.
| LeadSource | Rating | grpSource | grpRating | cnt |
|---|---|---|---|---|
| Web | Hot | 0 | 0 | 4 |
| Web | Cold | 0 | 0 | 6 |
| Web | null | 0 | 0 | 2 |
| null | Hot | 0 | 0 | 3 |
| Web | null | 0 | 1 | 12 |
| null | null | 0 | 1 | 3 |
| null | null | 1 | 1 | 15 |
Look at the three rows where both fields are null, or where Rating is null with LeadSource = Web:
Web, nullwith0, 0is the real group of web leads with no rating. It holds 2 leads.Web, nullwith0, 1is the subtotal for all web leads. It holds 12 leads.null, nullwith0, 1is the subtotal for leads with no source, which is 3 leads.null, nullwith1, 1is the grand total, which is 15 leads.
The visible values are identical across several rows. Only GROUPING separates them.
Reading GROUPING in Apex
GROUPING results come back through AggregateResult like any other aliased expression. Give each call an alias and read it with get. The value is numeric, so converting with Integer.valueOf avoids a bad cast.
for (AggregateResult ar : [
SELECT LeadSource, Rating,
GROUPING(LeadSource) grpSource,
GROUPING(Rating) grpRating,
COUNT(Id) cnt
FROM Lead
GROUP BY ROLLUP(LeadSource, Rating)
]) {
Integer grpSource = Integer.valueOf(ar.get('grpSource'));
Integer grpRating = Integer.valueOf(ar.get('grpRating'));
Integer cnt = (Integer) ar.get('cnt');
String label;
if (grpSource == 1 && grpRating == 1) {
label = 'GRAND TOTAL';
} else if (grpRating == 1) {
label = 'Subtotal for source ' + ar.get('LeadSource');
} else {
label = 'Source ' + ar.get('LeadSource')
+ ', rating ' + ar.get('Rating');
}
System.debug(label + ': ' + cnt);
}The branches run from the most specific condition to the least. In a rollup, grpSource = 1 always implies grpRating = 1, so the grand total check must come first. Otherwise the second branch would catch it.
Filtering with GROUPING in HAVING
You can put GROUPING in a HAVING clause to keep only certain row types. To return only subtotals per lead source and drop the detail rows and grand total:
SELECT LeadSource, COUNT(Id) cnt
FROM Lead
GROUP BY ROLLUP(LeadSource)
HAVING GROUPING(LeadSource) = 0With a single field, ROLLUP returns one row per source plus the grand total. Filtering on GROUPING(LeadSource) = 1 returns only the grand total. This is a cheap way to get one overall number alongside a breakdown if you do not want to loop and sum in Apex.
With two fields, the same idea selects a level:
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
GROUP BY ROLLUP(LeadSource, Rating)
HAVING GROUPING(Rating) = 1 AND GROUPING(LeadSource) = 0This returns only the per-source subtotal rows.
Rules and common mistakes
GROUPINGonly works with fields listed inGROUP BY ROLLUP(...)orGROUP BY CUBE(...). Passing a field that is not in that list, or usingGROUPINGin a plainGROUP BY, fails.- Always alias
GROUPING(...). Without an alias, Salesforce names the columnexpr0,expr1, and so on. The numbering depends on position and shifts when you edit the query. GROUPINGreturns a whole number, not a Boolean. Compare with= 1or= 0, not withtrue.- A subtotal row may display
null, but thenullis not a record value. Do not use it as a key to look up records, for example by passing it into aWHERE LeadSource = :valuefollow-up query. - Subtotal rows count against the same limits as other aggregate rows, and the
ROLLUPandCUBEfield-count limits still apply.ROLLUPaccepts up to three fields. Check the current SOQL reference for theCUBElimit in your API version.
When to use GROUPING
Use GROUPING when your code or report needs to treat detail rows and subtotal rows differently. Typical cases are building a report table where subtotals are bold, summing only detail rows to cross-check a total, and returning a specific subtotal level to a Lightning component.
If you only ever read the grand total, a separate query without GROUP BY is simpler to write and easier to read. If your data never has nulls in the grouped fields, you could detect subtotals by null, but that breaks as soon as a field becomes optional. GROUPING is safer.
Exercise
A query uses GROUP BY ROLLUP(Industry, Type) on Account and selects GROUPING(Industry) gi and GROUPING(Type) gt. One result row has Industry = 'Banking', Type = null, gi = 0, and gt = 1. What does the row represent? How would the row look different if some Banking accounts had no Type?
Show answer
It is the subtotal for all Banking accounts, across every Type, because gt = 1 means Type was aggregated away. If some Banking accounts had no Type, there would be an additional row with Industry = 'Banking', Type = null, gi = 0, and gt = 0. That row is a real group of accounts with a blank Type. The two rows look identical in the field values, and only GROUPING tells them apart.
Exercise
Write a query on Opportunity that groups by StageName and Type with ROLLUP, and returns only the rows that are subtotals per stage (not detail rows and not the grand total). Use aliases for the aggregate expressions.
Show answer
SELECT StageName, Type, COUNT(Id) cnt, GROUPING(StageName) gs, GROUPING(Type) gt FROM Opportunity GROUP BY ROLLUP(StageName, Type) HAVING GROUPING(StageName) = 0 AND GROUPING(Type) = 1