Salesforce Apex Tutorial Chapter 18: Apex SOSL Query
Salesforce Object Search Language (SOSL) is used to perform text searches in Salesforce records. Using SOSL, you can search fields across multiple standard and custom objects in Salesforce.
A SOSL query returns a list of lists of sObjects, where each list contains the results from the search for a particular sObject type. A SOSL query always returns results in the same order that was specified in the SOSL query. Whenever a SOSL query does not return any record for a specified sObject type, it is returned as an empty list in the search results.
SOSL Syntax includes:
With SOSL, you can specify search criteria such as:
- Enter a text expression (single word or phrase) for searching
- Scope of fields to search
- List of objects and fields to retrieve
- Conditions for selecting rows in the source objects
FIND 'SearchQuery' [IN SearchGroup] [RETURNING ObjectsAndFields]
- SOSL queries allow you to filter, reorder, and limit the returned results. SOSL queries can return several sObjects, therefore, those filters are applied to every sObject within the RETURNING clause.
- SOSL results can be filtered by adding conditions in the WHERE clause for an object.
- The ORDER BY option can also be applied to an object to order one sObject’s results.
- You can limit the number of returned records.
Let’s take an example that searches the text ‘Salesforce’ in Account, Contact, and opportunity fields.
List<List<sObject>> searchList = [FIND 'Salesforce' IN ALL FIELDS RETURNING Account(Name,Industry WHERE Industry='Chemical' LIMIT 1),Contact(FirstName,LastName),Opportunity(Name)];