Sub topic 7
Filtering and ordering results per object
This chapter assumes you can write a basic FIND ... RETURNING query. It covers how to filter, sort and page the records for each object in the RETURNING clause.
Where the clauses go
SOSL has no query-wide WHERE or ORDER BY. Each object in RETURNING takes its own conditions inside its own parentheses, after the field list:
ObjectName(field1, field2 WHERE condition ORDER BY field LIMIT n OFFSET n)You can give each object a different filter, sort and size. A WHERE clause placed after the closing parenthesis is a syntax error.
A worked example
This query searches name fields for a term held in a bind variable. It treats each of the three objects differently.
String term = 'Acme';
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING
Account(Id, Name WHERE Industry = 'Technology' ORDER BY Name LIMIT 5),
Contact(Id, Name, Email WHERE Email != null ORDER BY LastName NULLS LAST LIMIT 10),
Opportunity(Id, Name, Amount WHERE IsClosed = false ORDER BY Amount DESC LIMIT 3)
];
for (List<SObject> group : results) {
System.debug(group.size() + ' records of ' + group.getSObjectType());
}The result lists come back in the same order as the objects in RETURNING: accounts, contacts, then opportunities. Each list is filtered, sorted and capped on its own.
What each clause does
| Clause | Effect | Notes |
|---|---|---|
| `WHERE` | Keeps only matching records from that object | It can use fields that are not in the field list. |
| `ORDER BY` | Sorts that object's records | It replaces the default relevance order. Add `DESC`, `NULLS FIRST` or `NULLS LAST` as needed. |
| `LIMIT n` | Caps the number of records for that object | Use it to stop one object from filling the result. |
| `OFFSET n` | Skips the first n records for that object | Use it with `ORDER BY` and `LIMIT` for paging. |
Order of evaluation
The search matches the term first, and your WHERE clause then narrows those matches. A WHERE clause never widens the search. If Industry = 'Technology' removes every account that matched the term, the account list is empty.
Without ORDER BY, SOSL returns records ranked by relevance to the search term. This is usually what you want for a search box. Add ORDER BY only when the user expects a fixed order, because it discards the relevance ranking for that object.
Paging with OFFSET
To fetch the second page of five accounts, keep the same sort and move the offset:
List<List<SObject>> page2 = [
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name ORDER BY Name LIMIT 5 OFFSET 5)
];
List<Account> accounts = (List<Account>) page2[0];A stable ORDER BY matters here. Without one, the relevance order can differ between calls, so pages may overlap or skip records.
Common mistakes
- Putting
WHEREorORDER BYafter the lastRETURNINGobject and expecting it to apply to all objects. It applies to none of them. - Expecting a per-object
LIMITto be the only cap. ALIMITafter the wholeRETURNINGclause caps the total across all objects, and a single SOSL query also has a maximum number of returned rows. - Filtering on a field that is not searchable or not visible to the running user. The query fails or the records are excluded.
- Adding an object with no field list, such as
Account. It returns only theId, so any other field you read throws aSystem.SObjectException.
Exercise
Write the RETURNING clause that returns at most 20 open Cases (IsClosed = false), newest first by CreatedDate, and at most 5 Accounts sorted by Name. Which list is at index 1 of the result?
Show answer
RETURNING Case(Id, Subject WHERE IsClosed = false ORDER BY CreatedDate DESC LIMIT 20), Account(Id, Name ORDER BY Name LIMIT 5). The Account list is at index 1, because results follow the order of the objects in RETURNING and Case is first.