Sub topic 3
Ordering and Limiting Grouped Results
Assume you know basic SOQL, Salesforce objects, and simple Apex loops. Aggregate queries return one row per group, so ordering and limits apply to groups rather than individual records.
Ordering and Limiting Grouped Results
Order groups by an aggregate expression. LIMIT restricts the number of groups returned.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource
ORDER BY COUNT(Id) DESC
LIMIT 5This returns the five lead sources with the most leads. The alias leadCount makes the result easier to read in Apex, even though the query orders by the aggregate expression.
Grouping by Related Fields
You can group by a field on a related object by using relationship notation.
SELECT Account.Industry, COUNT(Id) opportunityCount
FROM Opportunity
GROUP BY Account.Industry
ORDER BY COUNT(Id) DESCEach group represents an account industry. Records with a null industry can form a null group.
Grouping by Calendar and Fiscal Date Parts
Date functions turn a date into a groupable part, such as a year or quarter.
SELECT CALENDAR_YEAR(CloseDate) year, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY CALENDAR_YEAR(CloseDate)
ORDER BY CALENDAR_YEAR(CloseDate)Use FISCAL_YEAR(CloseDate) or FISCAL_QUARTER(CloseDate) when reports must follow your Salesforce fiscal year settings.
Subtotals with ROLLUP
ROLLUP adds subtotal rows and a grand total while preserving the hierarchy of the fields.
SELECT LeadSource, Rating, COUNT(Id) total
FROM Lead
GROUP BY ROLLUP(LeadSource, Rating)The results include each LeadSource and Rating combination, a subtotal for each LeadSource, and one grand total.
Cross-Tabulated Subtotals with CUBE
CUBE produces subtotals for every combination of the grouped fields. It is useful for cross-tabulated summaries but can produce many rows.
SELECT LeadSource, Rating, COUNT(Id) total
FROM Lead
GROUP BY CUBE(LeadSource, Rating)Identifying Subtotal Rows
GROUPING(field) returns 1 when that field was aggregated into a subtotal and 0 for an ordinary group row.
SELECT LeadSource, Rating,
GROUPING(LeadSource) sourceSubtotal,
GROUPING(Rating) ratingSubtotal,
COUNT(Id) total
FROM Lead
GROUP BY ROLLUP(LeadSource, Rating)Limits and Common Pitfalls
- Every selected non-aggregate field must appear in
GROUP BY. - Give aggregate expressions aliases, especially when Apex reads them.
- Read grouped rows as
AggregateResult, not as ordinary sObjects. LIMITlimits groups, not source records.- Aggregate queries have row and governor limits. A query that creates many
CUBEcombinations can exceed those limits.
Exercise
Which clause filters individual records before grouping, and which clause filters completed groups?
Show answer
WHERE filters records before grouping. HAVING filters groups after aggregation.