Sub topic 13
Cross-tabulated subtotals with GROUP BY CUBE
This chapter assumes you can write basic SOQL with GROUP BY and aggregate functions, and that you have seen GROUP BY ROLLUP in the previous chapter. You should also be comfortable reading AggregateResult rows in Apex. Here you will learn what GROUP BY CUBE returns, how it differs from ROLLUP, how to read its output, and where it goes wrong.
What CUBE does
GROUP BY ROLLUP produces subtotals along a hierarchy. With ROLLUP(LeadSource, Rating) you get one row per source and rating pair, one subtotal row per source, and one grand total. You do not get a subtotal per rating alone, because rating is the second field in the hierarchy.
GROUP BY CUBE produces a subtotal for every combination of the grouped fields. With two fields, that means subtotals for each field on its own, plus the grand total. This is a cross-tabulation: you can read the totals along both axes of a table.
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
GROUP BY CUBE(LeadSource, Rating)For CUBE(LeadSource, Rating), the result contains four kinds of rows:
- Detail rows: one per distinct
LeadSourceandRatingpair. - Subtotal rows per
LeadSource, whereRatingisnull. - Subtotal rows per
Rating, whereLeadSourceisnull. - One grand total row, where both fields are
null.
The last two kinds are the ones ROLLUP does not give you.
How many grouping sets you get
Each grouping set is one way of grouping the data. CUBE over n fields generates 2 to the power n grouping sets. ROLLUP over n fields generates only n + 1.
| Fields | ROLLUP sets | CUBE sets |
|---|---|---|
| 1 | 2 | 2 |
| 2 | 3 | 4 |
| 3 | 4 | 8 |
With one field the two clauses behave the same way. From two fields onward, CUBE produces more rows. Choose it only when you need the subtotals along every axis.
Telling subtotal rows apart with GROUPING
In the output, a null in a grouped field can mean two different things. It can be a subtotal row, where the field was aggregated away. It can also be a detail row for records whose field value is actually empty. A lead with no LeadSource forms a real group where LeadSource is null.
The GROUPING function resolves this. It takes one grouped field and returns 1 if the field is aggregated away in that row, and 0 otherwise.
SELECT LeadSource, Rating,
GROUPING(LeadSource) grpSource,
GROUPING(Rating) grpRating,
COUNT(Id) cnt
FROM Lead
GROUP BY CUBE(LeadSource, Rating)You can interpret each row from the two flags:
| grpSource | grpRating | Meaning of the row |
|---|---|---|
| 0 | 0 | Detail row for one source and rating pair |
| 0 | 1 | Subtotal for one source, across all ratings |
| 1 | 0 | Subtotal for one rating, across all sources |
| 1 | 1 | Grand total |
A real null value in a detail row still has a flag of 0. Only a subtotal row has a flag of 1.
Reading CUBE results in Apex
In Apex, the rows come back as AggregateResult objects, as with any other grouped query. Read the flags with get, and cast them to Integer. Use them to decide how to label each row.
for (AggregateResult ar : [
SELECT LeadSource, Rating,
GROUPING(LeadSource) grpSource,
GROUPING(Rating) grpRating,
COUNT(Id) cnt
FROM Lead
GROUP BY CUBE(LeadSource, Rating)
]) {
Integer grpSource = (Integer) ar.get('grpSource');
Integer grpRating = (Integer) ar.get('grpRating');
Integer cnt = (Integer) ar.get('cnt');
String label;
if (grpSource == 1 && grpRating == 1) {
label = 'Grand total';
} else if (grpSource == 1) {
label = 'All sources, rating ' + ar.get('Rating');
} else if (grpRating == 1) {
label = 'Source ' + ar.get('LeadSource') + ', all ratings';
} else {
label = 'Source ' + ar.get('LeadSource') + ', rating ' + ar.get('Rating');
}
System.debug(label + ': ' + cnt);
}The fields without aliases, LeadSource and Rating, are read by their field names. Aliased expressions are read by alias.
Combining CUBE with WHERE and HAVING
WHERE filters records before any grouping happens, so subtotals and the grand total are computed only from the records that pass. HAVING filters rows after aggregation, and it applies to subtotal rows as well as detail rows. A condition such as HAVING COUNT(Id) > 10 can remove subtotal rows that are too small, which leaves gaps that are easy to misread.
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
WHERE IsConverted = false
GROUP BY CUBE(LeadSource, Rating)
HAVING COUNT(Id) > 10In this query, only unconverted leads are counted. Any row, detail or subtotal, with ten or fewer leads is dropped. The grand total survives unless fewer than eleven unconverted leads exist.
Ordering CUBE output
Subtotal rows are not guaranteed to appear in any useful order. To control the order, use ORDER BY on the grouped fields. In Salesforce, null values sort first by default in ascending order, which tends to put subtotal rows ahead of the detail rows for the same group. If you need a specific layout, sort in Apex after the query returns instead of relying on the database order.
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
GROUP BY CUBE(LeadSource, Rating)
ORDER BY LeadSource, RatingRestrictions and pitfalls
The following points cause most problems with CUBE.
- Row count grows quickly. Each added field doubles the number of grouping sets. A three-field cube over high-cardinality fields can produce far more rows than you expect. Check the output size before you use it in production code.
- Field count is limited.
ROLLUPsupports up to three fields.CUBEis limited to three fields as well. Query errors for more fields are reported at compile or run time. Confirm the current limits in the SOQL reference for your API version. - Use
GROUPINGinstead of testing fornull. Testingar.get('LeadSource') == nullmixes real empty values with subtotal rows. The flag is the dependable check. - Only some contexts support it.
ROLLUPandCUBEwork in SOQL queries on supported objects. They cannot be combined withGROUP BYin the same query for the same fields, and they are not supported in every query form. Do not use them in a subquery or withOFFSET. Test the exact query shape you need. - Governor limits still apply. An aggregate query returns up to 2,000 rows when you read it with a single
forloop over the query. Subtotal rows count toward the total returned. Aggregate queries also count against the SOQL query limit and the CPU limit. - Aliases matter. An unaliased aggregate such as
COUNT(Id)is returned under an automatic name likeexpr0. Reading it by that name is fragile, so always alias. - Choose CUBE only when you need it. If your report has one natural hierarchy, such as source then rating,
ROLLUPreturns fewer rows and does less work.
When to choose CUBE or ROLLUP
Use ROLLUP when the fields form a hierarchy, such as country, then state, then city. Use CUBE when the fields are independent dimensions and users want totals by each of them, such as source and rating, or region and product. If you only need one subtotal axis, a plain GROUP BY and a second query may be simpler and easier to read.
Exercise
A query uses GROUP BY CUBE(LeadSource, Rating) and selects GROUPING(LeadSource) grpSource and GROUPING(Rating) grpRating. One returned row has grpSource = 1 and grpRating = 0, with Rating = 'Hot'. What does this row represent, and how many grouping sets does this CUBE produce in total?
Show answer
The row is the subtotal of all leads with a rating of Hot, summed across every lead source, because LeadSource is aggregated away (flag 1) and Rating is kept (flag 0). CUBE over two fields produces 2 to the power 2, which is 4 grouping sets: source and rating, source only, rating only, and the grand total.
Exercise
Why is checking whether LeadSource is null an unreliable way to find subtotal rows in a CUBE result, and what should you use instead?
Show answer
Leads with no LeadSource form a real group in which LeadSource is null, so a null value can appear in a detail row as well as in a subtotal row. Use the GROUPING function on the field: it returns 1 only when the field is aggregated away in that row.