Sub topic 9
Ordering and limiting grouped results
This chapter assumes you know basic SOQL (SELECT, WHERE, ORDER BY, LIMIT), can write a GROUP BY query, and can read an AggregateResult in Apex. Here you will sort grouped rows, cut them down to a top-N list, and page through them. You will also see the rules that decide which expressions you may sort by.
Why ordering matters for grouped queries
A grouped query returns one row per group. SOQL does not promise any particular order for those rows. If you run the same query twice, the groups can come back in a different sequence. When you show a report, pick the "top" group, or compare results from one run to the next, you need an explicit ORDER BY.
ORDER BY and LIMIT run after grouping and aggregation. They act on the grouped rows, not on the underlying records. This is the reverse of WHERE, which filters records before they are grouped.
Ordering by a grouped field
The simplest case sorts by a field that appears in GROUP BY. This query lists lead counts by source, alphabetically.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource
ORDER BY LeadSourceYou can add ASC or DESC after each sort field. Ascending is the default. Rows where the field is null sort first in ascending order and last in descending order, unless you add NULLS FIRST or NULLS LAST.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSource
ORDER BY LeadSource ASC NULLS LASTLeads with no source form a single group where LeadSource is null. That group appears in the output like any other, so decide where you want it.
Ordering by an aggregate value
Most real requests sort by the number being computed, such as the biggest accounts first. Put the aggregate function in ORDER BY.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY AccountId
ORDER BY SUM(Amount) DESCRepeat the full expression, SUM(Amount), in the ORDER BY clause. In SOQL you can sort by the aggregate function itself, and COUNT(Id), AVG(Amount), MIN(CloseDate) and MAX(Amount) work the same way.
The alias is a label for reading results. Do not rely on it in ORDER BY. Writing ORDER BY total DESC is a common mistake carried over from SQL habits, and SOQL rejects it with an error.
SELECT StageName, COUNT(Id) cnt
FROM Opportunity
GROUP BY StageName
ORDER BY COUNT(Id) DESC, StageNameThis query has two sort keys. The first sorts by group size, largest first. The second breaks ties alphabetically, so the order is the same on every run.
Ordering rules
| You want to sort by | Allowed in ORDER BY | Example |
|---|---|---|
| A field in GROUP BY | Yes | `ORDER BY StageName` |
| An aggregate function | Yes | `ORDER BY COUNT(Id) DESC` |
| An alias of an aggregate | No | `ORDER BY cnt` fails |
| A field not in GROUP BY and not aggregated | No | `ORDER BY Amount` fails |
| A date function used in GROUP BY | Yes, repeat the function | `ORDER BY CALENDAR_YEAR(CloseDate)` |
The last row matters for date grouping. If you group by CALENDAR_YEAR(CloseDate), sort by the same expression, as in the date example from earlier chapters.
SELECT CALENDAR_YEAR(CloseDate) yr, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY CALENDAR_YEAR(CloseDate)
ORDER BY CALENDAR_YEAR(CloseDate)Limiting the number of groups
LIMIT caps the number of grouped rows returned. Combined with a descending aggregate sort, it gives you a top-N list. This query returns the five accounts with the highest won revenue.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY AccountId
ORDER BY SUM(Amount) DESC
LIMIT 5Always place ORDER BY before LIMIT. Without a sort, LIMIT 5 returns five groups, but you cannot say which five.
Ties can cross the cut line. If the fifth and sixth accounts have the same total, only one of them is returned, and which one can vary. Add a second sort key such as AccountId when you need a stable result.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY AccountId
ORDER BY SUM(Amount) DESC, AccountId
LIMIT 5Paging with OFFSET
OFFSET skips a number of groups before returning rows. Together with LIMIT, it reads a result in pages. This query returns groups 11 to 20.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true
GROUP BY AccountId
ORDER BY SUM(Amount) DESC, AccountId
LIMIT 10 OFFSET 10Paging only works reliably with a complete, deterministic ORDER BY. If two groups tie and nothing separates them, a group can appear on two pages or on none.
Each page runs the full aggregation again. Data can also change between page requests, so a group may move to a different page. For a small ranked list, LIMIT is a good fit. For long result lists, check the current limits on OFFSET in the SOQL documentation for your API version.
Limits that apply to aggregate queries
Aggregate queries count against the same governor limits as other SOQL, with a few differences.
- Each query counts as one SOQL query, however many groups it returns.
- Each grouped row returned counts toward the limit on total rows retrieved in a transaction, not the number of records that were summed. A query that summarizes 40,000 opportunities into 8 stages counts as 8 rows.
- Aggregate queries that do not use
LIMITcan still fail if they scan too many records or return too many groups. A selectiveWHEREclause reduces this risk. LIMITreduces the rows returned, but the database may still read the records needed to compute each group.
Using ordered results in Apex
The order of rows in the AggregateResult list follows your ORDER BY. In Apex you can put the query in a loop and read each row in sequence. Read values by alias, and cast them.
List<AggregateResult> topAccounts = [
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsWon = true AND AccountId != null
GROUP BY AccountId
ORDER BY SUM(Amount) DESC, AccountId
LIMIT 3
];
Integer rank = 1;
for (AggregateResult ar : topAccounts) {
Id accountId = (Id) ar.get('AccountId');
Decimal total = (Decimal) ar.get('total');
System.debug('#' + rank + ' ' + accountId + ' won ' + total);
rank++;
}The sort uses SUM(Amount), and the alias total is used only for reading the value. Notice the filter AccountId != null. Without it, opportunities with no account form one group, which could take a place in your top three.
Common mistakes
- Sorting by an alias instead of the aggregate expression.
- Using
LIMITwith noORDER BYand expecting a "top" result. - Leaving out a tie-breaker, so paged results shift between runs.
- Forgetting that a null group is a real row that can occupy a place in a top-N list.
- Sorting by a field that is neither grouped nor aggregated.
Exercise
Write a SOQL query that returns the three lead sources with the most leads, largest first. Leads with no source must not appear. Break ties by LeadSource, and explain why ORDER BY leadCount DESC would not work if you wrote COUNT(Id) leadCount.
Show answer
SELECT LeadSource, COUNT(Id) leadCount FROM Lead WHERE LeadSource != null GROUP BY LeadSource ORDER BY COUNT(Id) DESC, LeadSource LIMIT 3. The WHERE clause removes null-source leads before grouping, so they never form a group. ORDER BY must repeat the aggregate expression COUNT(Id), because SOQL does not accept an aggregate alias as a sort key. The second key, LeadSource, makes the order stable when two sources have equal counts.
Exercise
A query groups won opportunities by AccountId, orders by SUM(Amount) DESC, and uses LIMIT 10 OFFSET 10. Two accounts tie on total at the boundary between pages 1 and 2. What can go wrong, and how do you fix it?
Show answer
With no tie-breaker, the database may order the tied accounts differently on each run, so one account can show on both pages or on neither. Add a second sort key that is unique per group, such as AccountId: ORDER BY SUM(Amount) DESC, AccountId.