Sub topic 1
What SOSL is and how it searches
Salesforce Object Search Language (SOSL) searches text across several objects and fields in one query. This chapter covers what happens when a SOSL query runs, why its results can differ from a SOQL filter, and what to expect from the search index behind it. Later chapters cover the clauses in detail.
Prerequisites
This chapter assumes you already know:
- The Salesforce data model: objects, fields, and records.
- Basic SOQL:
SELECT,WHERE,ORDER BY, andLIMIT. - Basic Apex: variables, collections, and loops.
- How to run anonymous Apex or use the Developer Console.
What SOSL is
SOSL is a query language for text search. You give it a word or phrase, and it looks for matches across many objects and fields at once. SOQL reads rows from the database. SOSL reads from a separate search index.
A SOSL query has two required ideas:
- What to look for. This is the search term, written in a
FINDclause. - What to return. This is a list of objects and fields, written in a
RETURNINGclause.
Here is a first query. Run it in anonymous Apex:
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)
];
List<Account> accounts = (List<Account>) results[0];
List<Contact> contacts = (List<Contact>) results[1];
System.debug(accounts.size() + ' accounts, ' + contacts.size() + ' contacts');The query searches the name fields of Account and Contact for terms that start with Acme. The result is a list of lists. results[0] holds the accounts and results[1] holds the contacts, because that is the order of the objects in RETURNING. Doing this with SOQL would take two separate queries, one for each object.
How the search index works
SOSL does not scan your tables. When you create or update a record, Salesforce copies the text of its searchable fields into a search index. A SOSL query looks up your terms in that index and then loads the matching records.
The index shapes how SOSL behaves:
- Text is split into tokens. The index stores words, not whole field values. A search for
Corpcan match an account namedAcme Corp InternationalbecauseCorpis one of its words. - Matching is case-insensitive.
acme,ACME, andAcmefind the same records. - Matching is word-based and can be linguistic. The search can match related forms of a word, such as
runningandrun. A SOQLLIKEdoes literal pattern matching only. - Only some fields are indexed. Text-like fields such as names, email, phone, and text areas are searchable. Numbers, dates, and checkboxes are not searched by
FIND. You can still filter on them with aWHEREinsideRETURNING. - Only some objects are searchable. Standard objects such as Account, Contact, Lead, Opportunity, and Case are. Custom objects are searchable unless they are marked otherwise. An object that is not searchable cannot appear in
RETURNING. - Very short terms are a problem. A search term needs at least two characters, excluding wildcards.
flowchart LRThe diagram below shows the full path of a record and a query.
The index is updated after a delay
Saving a record does not update the index in the same moment. The index is refreshed shortly after the save commits. In practice the delay is usually seconds, but it can be longer under load or after a bulk load.
This has three effects:
- A record you just inserted may not appear in a SOSL query that runs right afterward.
- A record you just edited may match its old text, not its new text, for a short time.
- A deleted record can briefly still be in the index. Salesforce does not return deleted records, so you will not see them in results.
SOQL has none of these problems, because it reads the database directly and sees your changes at once.
This also affects Apex tests. Records created inside a test are not reliably searchable, so a SOSL query in a test may return nothing even though the record exists. A later chapter shows how to handle that with Test.setFixedSearchResults.
What a result looks like
A SOSL query in Apex always returns List<List<SObject>>. The outer list has one entry per object in RETURNING, in the order you wrote them. Each inner list holds the matching records of that object, and it is empty when nothing matched. The outer list still has its entry in that case, so results[0] is safe to read even when there are no hits.
Because the inner lists are typed as SObject, you cast them to the concrete type:
List<List<SObject>> results = [
FIND 'Smith' IN NAME FIELDS
RETURNING Contact(Id, FirstName, LastName), Lead(Id, FirstName, LastName)
];
for (List<SObject> group : results) {
System.debug('Group size: ' + group.size());
}
for (Contact c : (List<Contact>) results[0]) {
System.debug('Contact: ' + c.FirstName + ' ' + c.LastName);
}The loop over results is useful when you want to treat every object the same way. The cast is needed when you want object-specific fields.
Each record in the result contains only the fields you listed in RETURNING, plus its Id. Reading a field you did not list throws a System.SObjectException. This is the same rule as in SOQL.
Results are ranked, not just filtered
A SOQL WHERE clause gives a yes or no for each record. SOSL scores each match, and within an object it returns the better matches first unless you add an ORDER BY in the RETURNING clause. How well a record matches depends on how the term appears in it, so a record whose name matches fully usually ranks above one that matches a word in a long text field. The exact scoring is not documented, so do not depend on a particular order. If you need a fixed order, specify it.
Limits to know from the start
SOSL has limits that SOQL does not. The values below are the standard Apex governor limits. Check the current Salesforce documentation for your release.
| Limit | Value |
|---|---|
| SOSL queries per synchronous transaction | 20 |
| Records returned by one SOSL query | 2,000 |
| Minimum length of a search term | 2 characters |
The 2,000-record cap is the one that surprises people. A SOSL query is meant to return the best matches, not every match. If you need to process every record that meets a condition, use SOQL, which can page through large result sets.
Where SOSL fits
SOSL is a good fit when:
- You do not know which object or field holds the text.
- You want one search box that covers several objects.
- You want fuzzy, word-based matching with ranking.
SOQL is a better fit when:
- You need every matching record, not the top matches.
- You filter on numbers, dates, picklist values, or relationships.
- You need to see changes you just saved.
- You need aggregates such as
COUNT()orGROUP BY.
The next chapter compares the two in more detail. For now, remember the rule of thumb: use SOSL to find text, and SOQL to retrieve data.
Worked example: one search box
Suppose a support agent types part of a customer name into a search box. You want to show matching accounts, contacts, and leads together. Here is a minimal version for anonymous Apex:
String term = 'Globex*';
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING
Account(Id, Name),
Contact(Id, Name),
Lead(Id, Name)
];
String[] labels = new String[] { 'Account', 'Contact', 'Lead' };
for (Integer i = 0; i < results.size(); i++) {
for (SObject rec : results[i]) {
System.debug(labels[i] + ': ' + rec.get('Name'));
}
}Points to notice:
- One query covers three objects. That uses one of your 20 SOSL queries, where three SOQL queries would use three of your 100.
- The
labelsarray lines up with theRETURNINGorder. If you reorderRETURNING, reorderlabelstoo. rec.get('Name')works on the genericSObject, so no cast is needed.- The
:termis a bind variable. Later chapters cover bind variables and dynamic queries.
Common errors
- Reading
results[1]when you listed one object. This throws aSystem.ListException. The outer list has exactly as many entries asRETURNINGhas objects. - Expecting a fresh insert to be found. The index lags. Query by ID with SOQL when you already have the record.
- Expecting all matches. The 2,000-record cap truncates results without an error.
- Searching a numeric or date field with
FIND. Those fields are not indexed for search. Use aWHEREfilter inRETURNING. - A one-character search term. Terms must have at least two characters.
Exercise
A developer inserts an Account named "Initech Holdings" and, in the same transaction, runs a SOSL query FIND 'Initech*' IN NAME FIELDS RETURNING Account(Id, Name). The list comes back empty. Why, and what should the developer do if the goal is to confirm the record exists?
Show answer
SOSL reads the search index, and the index is updated shortly after the save commits, so the new record is not yet searchable. To confirm the record exists, query it by ID with SOQL (or use the ID returned by the insert), because SOQL reads the database directly and sees the change at once.
Exercise
A query ends with RETURNING Contact(Id, Name), Account(Id, Name). Which index of the result holds the accounts, and what happens if no accounts match?
Show answer
The accounts are in results[1], because the result lists follow the order of RETURNING. If nothing matches, results[1] is still present and is an empty list.