Sub topic 9
Ordering and limiting grouped results
This chapter assumes you can write a basic aggregate query with GROUP BY and know that WHERE filters rows and HAVING filters groups. Here you will sort grouped rows and cut the result down to the rows you need.
Why order and limit
A GROUP BY query returns one row per group. Without ORDER BY, the order of those rows is not guaranteed. Reports such as "top five lead sources" need an explicit sort and a row cap.
The clauses run in a fixed sequence. LIMIT counts groups, not the records inside them.
Ordering by an aggregate
To rank groups by size, put the aggregate expression in ORDER BY.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource
ORDER BY COUNT(Id) DESCRepeat the full expression, COUNT(Id). Do not write the alias leadCount in ORDER BY. The alias names the result column for your Apex code and is not accepted as a sort key.
Ordering by a grouped field
You can also sort by any field listed in GROUP BY. This query returns industries in alphabetical order.
SELECT Industry, AVG(AnnualRevenue) avgRevenue
FROM Account
GROUP BY Industry
ORDER BY Industry ASC NULLS LASTRecords with a blank Industry form their own group with a null value. NULLS LAST moves that group to the end. Use NULLS FIRST to put it at the top.
Limiting the result
LIMIT keeps the first N rows after sorting. Combine it with ORDER BY to get a top-N list.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource
ORDER BY COUNT(Id) DESC
LIMIT 5This returns at most five rows, the five lead sources with the most leads. Without ORDER BY, LIMIT 5 returns five arbitrary groups.
Using it from Apex
The same query works in Apex. Read each row with get, using the alias.
List<AggregateResult> rows = [
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource
ORDER BY COUNT(Id) DESC
LIMIT 5
];
for (AggregateResult ar : rows) {
System.debug((String) ar.get('LeadSource') + ': ' + (Integer) ar.get('leadCount'));
}Common errors
| Mistake | Result | Fix |
|---|---|---|
| Sorting by a field that is not in `GROUP BY` and is not aggregated | Query error | Add the field to `GROUP BY` or wrap it in an aggregate |
| Sorting by the alias | Query error | Repeat the aggregate expression in `ORDER BY` |
| Using `LIMIT` without `ORDER BY` | Arbitrary groups returned | Add an `ORDER BY` that defines "top" |
| Expecting `LIMIT` to cap the records read | All matching records are still aggregated | Narrow the data with `WHERE` |
Exercise
Write a query that returns the three Account industries with the highest total AnnualRevenue, largest first. Why must ORDER BY repeat SUM(AnnualRevenue) instead of using an alias?
Show answer
SELECT Industry, SUM(AnnualRevenue) totalRevenue FROM Account GROUP BY Industry ORDER BY SUM(AnnualRevenue) DESC LIMIT 3. The alias only names the column in the result, such as for ar.get('totalRevenue') in Apex. SOQL needs the actual expression to sort on.