Sub topic 5
Sorting and limiting results
This chapter assumes you can write an inline SOQL query with a WHERE clause and loop over the returned list. It adds ORDER BY, LIMIT, and OFFSET, which control the order and size of the result.
Sorting with ORDER BY
SOQL does not guarantee any row order unless you ask for one. Add ORDER BY after WHERE to sort. The default direction is ascending (ASC). Use DESC for descending.
List<Account> accts = [
SELECT Id, Name, AnnualRevenue
FROM Account
WHERE Industry = 'Technology'
ORDER BY AnnualRevenue DESC
];You can sort by several fields. SOQL applies them left to right, and later fields break ties in earlier ones.
List<Contact> contacts = [
SELECT Id, LastName, FirstName
FROM Contact
ORDER BY LastName ASC, FirstName ASC
];You can also sort by a parent field with dot notation, such as ORDER BY Account.Name.
Null values
Ascending sorts put null values first. Descending sorts put them last. Use NULLS FIRST or NULLS LAST to override this. Without it, accounts with no revenue can fill the top of an ascending list.
List<Account> accts = [
SELECT Id, Name, AnnualRevenue
FROM Account
ORDER BY AnnualRevenue ASC NULLS LAST
];Sorting gotchas
- A picklist field sorts by the order of its values in the field definition, not alphabetically.
- You cannot sort on some field types, such as long text areas and multi-select picklists.
- Sorting uses the database, so it costs nothing against your Apex CPU time. Prefer it over sorting a list in Apex.
Limiting with LIMIT
LIMIT caps the number of rows returned. Paired with ORDER BY, it gives a "top N" query.
List<Opportunity> top5 = [
SELECT Id, Name, Amount
FROM Opportunity
WHERE Amount != null
ORDER BY Amount DESC
LIMIT 5
];Without ORDER BY, LIMIT 5 returns five rows in no reliable order. The same query can return different rows later. Always sort when the choice of rows matters.
LIMIT also accepts a bind variable:
Integer maxRows = 20;
List<Account> accts = [
SELECT Id, Name FROM Account ORDER BY Name LIMIT :maxRows
];LIMIT does not change the governor limit on queries. It still counts as one query. It does reduce the rows retrieved and the heap memory used.
Paging with OFFSET
OFFSET skips a number of rows before returning results. Use it with ORDER BY and LIMIT to fetch page by page.
Integer pageSize = 10;
Integer pageNumber = 3; // first page is 1
Integer skip = (pageNumber - 1) * pageSize;
List<Account> page = [
SELECT Id, Name
FROM Account
ORDER BY Name, Id
LIMIT :pageSize
OFFSET :skip
];Adding Id as a final sort field makes the order stable when names repeat. Otherwise, rows with equal names could appear on two pages or on none.
The maximum offset is 2,000 rows. For deeper paging, filter on the last value you saw instead, for example WHERE Name > :lastName, or use a SOQL for loop.
Quick reference
| Clause | Purpose | Notes |
|---|---|---|
| `ORDER BY field` | Sort results | `ASC` is the default |
| `NULLS FIRST` / `NULLS LAST` | Place null values | Overrides the default null placement |
| `LIMIT n` | Cap the row count | Accepts a bind variable |
| `OFFSET n` | Skip rows | Maximum 2,000 |
Exercise
Write a query that returns the three Accounts with the highest AnnualRevenue, ignoring Accounts where AnnualRevenue is null. Why is ORDER BY needed here?
Show answer
[SELECT Id, Name, AnnualRevenue FROM Account WHERE AnnualRevenue != null ORDER BY AnnualRevenue DESC LIMIT 3]. Without ORDER BY, LIMIT 3 returns three rows in no guaranteed order, so they would not be the highest-revenue accounts.