Sub topic 11
Governor Limits, Sharing, and Field Access
This chapter assumes you can write a basic FIND and RETURNING query, run SOSL in Apex, and read the List<List<SObject>> result. It covers three things that decide whether SOSL code works in production: the governor limits that cap it, the sharing rules that decide which records appear, and the field-level checks that decide which values you may expose.
SOSL governor limits
Apex enforces per-transaction limits. The ones that matter most for SOSL are below. Limits can change between releases, so confirm the numbers in the current Apex Developer Guide.
| Limit | Synchronous Apex | Asynchronous Apex |
|---|---|---|
| SOSL queries issued | 20 | 20 |
| Records returned by a single SOSL query | 2,000 | 2,000 |
| Heap size | 6 MB | 12 MB |
| CPU time | 10,000 ms | 60,000 ms |
Two points are easy to miss.
- The SOSL query count is separate from the SOQL query count. A transaction can run 100 SOQL queries and 20 SOSL queries.
- The 2,000-record cap applies to the whole query, not to each object in RETURNING. Salesforce returns at most 2,000 rows in total across all object lists, so adding more objects does not give you more rows.
Each Search.query call and each static [FIND ...] expression counts as one SOSL query. A static query inside a loop counts once per iteration.
Checking consumption at run time
The Limits class reports how much of each limit you have used. Use it while debugging, or to stop a loop before it fails.
System.debug('SOSL queries used: ' + Limits.getSoslQueries()
+ ' of ' + Limits.getLimitSoslQueries());
System.debug('Query rows used: ' + Limits.getQueryRows()
+ ' of ' + Limits.getLimitQueryRows());SOSL rows also count toward the total query rows limit, which is 50,000 per transaction. Check Limits.getQueryRows() if one transaction mixes SOQL and SOSL.
Avoid SOSL inside loops
The most common limit failure is a search per record. Here is the pattern to avoid.
// Fails with "Too many SOSL queries: 21" for 21 or more names.
public static void searchEachName(List<String> names) {
for (String n : names) {
List<List<SObject>> r = [FIND :n IN NAME FIELDS RETURNING Account(Id)];
}
}Combine the terms into one query with OR instead. The next example builds one search string from many names.
public with sharing class BulkNameSearch {
public static List<Account> findAll(List<String> names) {
List<String> quoted = new List<String>();
for (String n : names) {
quoted.add('"' + String.escapeSingleQuotes(n) + '"');
}
String term = String.join(quoted, ' OR ');
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name LIMIT 200)
];
return (List<Account>) results[0];
}
}Because the search term is a bind variable, it is not parsed as part of the query text. The quotes and the OR in the string are still read as search syntax, which is what we want here.
How the result size is capped
Without a LIMIT, a SOSL query returns up to 2,000 records in total. With per-object LIMIT clauses, each list is trimmed first. If the totals still exceed the cap, results are cut off.
To control the balance between objects, set a LIMIT on each one. If you do not, the object that matches most strongly can crowd out the others.
Sharing in SOSL
SOSL respects sharing depending on the class that runs it.
| Class declaration | Sharing behavior |
|---|---|
| `with sharing` | The search returns only records the running user can see. |
| `without sharing` | The search returns all matching records, ignoring record sharing. |
| `inherited sharing` | The class uses the sharing of the caller. If it is the entry point, it runs `with sharing`. |
| No keyword | Inherits from the caller. Entry points such as triggers and anonymous Apex run in system context for sharing purposes, so treat this as `without sharing`. |
Declare the sharing mode explicitly. A class with no keyword changes behavior depending on who calls it, which makes security bugs hard to find.
public with sharing class SafeSearch {
public static List<Contact> byName(String term) {
List<List<SObject>> r = [
FIND :term IN NAME FIELDS
RETURNING Contact(Id, Name, Email)
];
return (List<Contact>) r[0];
}
}Two details about sharing:
with sharingenforces record visibility only. It does not check object permissions or field permissions. A user with no read access to Contact can still, in some contexts, get results from awith sharingclass unless you add the checks in the next section.- The search index is independent of sharing. A record can be indexed and matched, then removed from results when sharing is applied. A query that matches many records the user cannot see can therefore return fewer rows than the LIMIT, even though more matches exist.
Object and field access
Apex runs in system mode by default. Object permissions and field-level security (FLS) are not enforced unless you ask for it. There are three ways to ask.
WITH USER_MODE
Add WITH USER_MODE to the SOSL query to enforce the running user's object permissions, field-level security, and sharing rules. This is the simplest option in current API versions.
public with sharing class UserModeSearch {
public static List<Account> find(String term) {
List<List<SObject>> r = [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name, AnnualRevenue)
WITH USER_MODE
];
return (List<Account>) r[0];
}
}If the user cannot read AnnualRevenue, the query throws a System.QueryException rather than quietly omitting the field. Catch the exception when you want to handle that case.
WITH SECURITY_ENFORCED
WITH SECURITY_ENFORCED is an older option that checks field and object access for the fields in the query. It is still supported, but WITH USER_MODE is preferred for new code because it also enforces sharing and covers more cases.
Stripping inaccessible fields
When you would rather remove fields the user cannot see than fail, use Security.stripInaccessible.
public with sharing class StripSearch {
public static List<Contact> find(String term) {
List<List<SObject>> r = [
FIND :term IN NAME FIELDS
RETURNING Contact(Id, Name, Email, Phone)
];
SObjectAccessDecision decision = Security.stripInaccessible(
AccessType.READABLE, r[0]
);
return (List<Contact>) decision.getRecords();
}
}Reading a stripped field on a returned record afterward gives an error, because the field is removed from the record rather than set to null. Check getRemovedFields() on the decision if you need to report what was removed.
Choosing an approach
| Goal | Use |
|---|---|
| Fail loudly when access is missing | `WITH USER_MODE` |
| Return what the user may see and drop the rest | `Security.stripInaccessible` |
| Maintain code that already uses it | `WITH SECURITY_ENFORCED` |
Searching without sharing on purpose
Sometimes a search must see more than the user does, such as a duplicate check across all accounts. Put that logic in a small without sharing class and return only what the caller needs, for example a count or a Boolean. Do not return full records from a without sharing search to a user-facing page.
public without sharing class DuplicateCheck {
public static Boolean accountExists(String name) {
String term = '"' + String.escapeSingleQuotes(name) + '"';
List<List<SObject>> r = [
FIND :term IN NAME FIELDS
RETURNING Account(Id LIMIT 1)
];
return !r[0].isEmpty();
}
}Common errors
- Too many SOSL queries: 21. A search runs inside a loop. Combine the terms with OR or batch them.
- Fewer results than expected. Sharing removed records, or the search index has not caught up with recent inserts. SOSL indexing is not instant, so a record created seconds ago may not match yet.
- QueryException on a field.
WITH USER_MODEfound a field the user cannot read. Remove the field, or switch tostripInaccessible. - A search term shorter than two characters. SOSL rejects very short terms. Validate input length before you search.
- Tests that return nothing. New records are not reliably searchable during a test. Use
Test.setFixedSearchResults, covered in the testing chapter.
Exercise
A class with no sharing keyword runs a SOSL search from a Lightning component controller. It calls RETURNING Contact(Id, Name, Salary__c). Name two problems with this setup for a user without access to Salary__c, and give a fix for each.
Show answer
First, the sharing mode is undeclared, so record visibility depends on the caller. Declare the class with sharing (or inherited sharing deliberately). Second, field-level security is not enforced in system mode, so Salary__c can be exposed. Add WITH USER_MODE to the query, or pass the results through Security.stripInaccessible(AccessType.READABLE, ...).
Exercise
You must look up 60 customer names in one transaction. Why does a loop with one SOSL query per name fail, and how would you restructure it?
Show answer
A synchronous transaction allows 20 SOSL queries, so the loop fails at the 21st name. Join the names with OR into a quoted search string and run one query, or split the names into three batches of 20 and run three queries. Set a LIMIT per object so the 2,000-record cap does not hide results.