Sub topic 5
Sorting and limiting results
This chapter assumes you can write an inline query with SELECT, FROM, and WHERE, and that you know how Apex lists and bind variables work. It covers the three clauses that shape which rows come back and in what order: ORDER BY, LIMIT, and OFFSET.
Where the clauses go
SOQL requires its clauses in a fixed order. ORDER BY follows WHERE (and GROUP BY and HAVING, if present). LIMIT follows ORDER BY, and OFFSET comes last.
The database filters rows first, sorts what remains, and then keeps only the slice you asked for. LIMIT never changes which rows are sorted. It only cuts the sorted result.
Sorting with ORDER BY
ORDER BY takes one or more fields. Each field sorts ascending (ASC) by default, and DESC reverses it.
List<Account> accts = [
SELECT Id, Name, AnnualRevenue
FROM Account
WHERE Industry = 'Technology'
ORDER BY AnnualRevenue DESC
];Sorting by several fields
List fields separated by commas. Each field has its own direction. Later fields only break ties left by earlier ones.
List<Contact> contacts = [
SELECT Id, LastName, FirstName, Account.Name
FROM Contact
ORDER BY Account.Name ASC, LastName ASC, FirstName ASC
];This example also shows that you can sort by a parent field through dot notation.
Null values
Fields without a value are null. By default, nulls sort first. In a descending revenue list, that puts accounts with no revenue at the top, which is rarely what you want. Add NULLS LAST to control it.
List<Account> accts = [
SELECT Id, Name, AnnualRevenue
FROM Account
ORDER BY AnnualRevenue DESC NULLS LAST
];Put NULLS FIRST or NULLS LAST after the direction, one per field.
What sorts and what does not
- Picklist fields sort by the order of the values in the picklist definition, not alphabetically.
- You cannot sort by long text areas, rich text areas, multi-select picklists, or other fields that Salesforce marks as not sortable. The query fails with a
QueryException. - You can sort by an aggregate expression, such as
ORDER BY COUNT(Id) DESC, in a grouped query.
Limiting with LIMIT
LIMIT sets the maximum number of rows returned. Pair it with ORDER BY to get a "top N" result.
List<Opportunity> top5 = [
SELECT Id, Name, Amount
FROM Opportunity
WHERE Amount != null
ORDER BY Amount DESC
LIMIT 5
];LIMIT accepts a bind variable, so the size can come from a method parameter.
public static List<Opportunity> largestOpportunities(Integer howMany) {
return [
SELECT Id, Name, Amount
FROM Opportunity
WHERE Amount != null
ORDER BY Amount DESC
LIMIT :howMany
];
}LIMIT and governor limits
Two limits matter here:
- A transaction can retrieve at most 50,000 rows across all its queries. A
LIMITsmaller than the number of matching rows keeps you well under that. LIMITdoes not reduce the number of queries. A query inside a loop still counts once per run, whatever itsLIMIT. Chapter topics on bulk-safe patterns cover that problem.
Getting a single record
For "the most recent" or "the largest" record, combine a sort, LIMIT 1, and a list. Checking isEmpty() avoids the QueryException that a direct single-record assignment throws when nothing matches.
List<Case> latest = [
SELECT Id, Subject, CreatedDate
FROM Case
WHERE AccountId = :accountId
ORDER BY CreatedDate DESC
LIMIT 1
];
if (!latest.isEmpty()) {
System.debug('Latest case: ' + latest[0].Subject);
}Paging with OFFSET
OFFSET skips a number of rows before returning results. Use it with LIMIT to build pages.
Integer pageSize = 20;
Integer pageNumber = 3;
Integer skipRows = (pageNumber - 1) * pageSize;
List<Account> page = [
SELECT Id, Name
FROM Account
ORDER BY Name, Id
LIMIT :pageSize
OFFSET :skipRows
];Three rules apply:
OFFSETneeds a stable sort. If two rows tie onName, their relative order may differ between page requests, so a row can appear on two pages or on none. AddingIdas the last sort field makes every row's position unique.- The largest allowed offset in Apex is 2,000. A larger value throws a
QueryException. - Skipped rows are still read by the database. Deep offsets are slower than shallow ones, and the skipped rows still count toward the 50,000-row limit.
Paging past 2,000 rows
When you must walk a larger set, filter on the last Id you saw instead of using an offset. This is called keyset paging.
public static List<Account> nextPage(Id lastSeenId, Integer pageSize) {
if (lastSeenId == null) {
return [SELECT Id, Name FROM Account ORDER BY Id LIMIT :pageSize];
}
return [
SELECT Id, Name
FROM Account
WHERE Id > :lastSeenId
ORDER BY Id
LIMIT :pageSize
];
}Each call starts where the previous page ended, so the cost does not grow with the page number. The trade-off is that you can only move forward in Id order and cannot jump to page 40 directly. If users need a custom sort order across many pages, offset paging with a cap, or a SOQL for loop for server-side processing, is usually the better fit.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `LIMIT 1` with no `ORDER BY` | An arbitrary row is returned | Add a sort that defines "first" |
| Sorting on a nullable field in descending order | Nulls appear first | Add `NULLS LAST` |
| `OFFSET` with a non-unique sort | Rows repeat or vanish between pages | Add `Id` as the final sort field |
| `OFFSET` above 2,000 | `QueryException` | Use keyset paging on `Id` |
| Sorting a long text field | `QueryException` | Sort by another field, or sort the list in Apex |
| Assigning a `LIMIT 1` query to one sObject | `QueryException` when no row matches | Assign to a list and check `isEmpty()` |
Sorting in Apex instead
When you already have a list and need a different order, you do not need another query. Apex can sort lists of sObjects only through a Comparable implementation, so use SOQL for the sort when you can. A second query costs one SOQL statement, while a custom comparer costs CPU time. Prefer one well-ordered query up front over re-sorting later.
Exercise
A page shows 25 accounts per page, sorted by Name. Users report that some accounts show up on two pages while others never appear. The query ends with ORDER BY Name LIMIT 25 OFFSET :skipRows. What is the likely cause, and what is the fix?
Show answer
Several accounts share the same Name, so their relative order is not guaranteed and can differ between page requests. Make the sort unique by adding Id as the last sort field: ORDER BY Name, Id LIMIT 25 OFFSET :skipRows.
Exercise
Write a query that returns the three open opportunities with the highest Amount, placing any opportunities with a null Amount after those with values. Assume the standard IsClosed field.
Show answer
[SELECT Id, Name, Amount FROM Opportunity WHERE IsClosed = false ORDER BY Amount DESC NULLS LAST LIMIT 3]
Exercise
Why does Integer n = 5000; [SELECT Id FROM Account ORDER BY Id LIMIT 10 OFFSET :n] fail, and what approach lets you reach rows past that position?
Show answer
The maximum OFFSET in Apex is 2,000, so 5000 throws a QueryException. Use keyset paging instead: filter with WHERE Id > :lastSeenId, sort by Id, and apply LIMIT.