About SOSL
Use the Salesforce Object Search Language (SOSL) to construct text-based search queries
against the search index.
You can search text, email, and phone fields for multiple objects, including custom objects, that you have access to in a single query in the following environments.
- SOAP or REST calls
- Apex statements
- Visualforce controllers and getter methods
- Schema Explorer of the Eclipse Toolkit
Compare SOSL and SOQL
Use SOQL when:
- You want to search against the org’s database. Results from a database search include matches for the exact search string.
- You know in which objects or fields the data resides.
- You want to:
- Retrieve data from a single object or from multiple objects that are related to one another
- Count the number of records that meet specified criteria
- Sort results as part of the query
- Retrieve data from number, date, or checkbox fields
Use SOSL when:
- You don’t know in which object or field the data resides, and you want to find it in the most efficient and fastest way possible.
- You want to:
- Retrieve data for a specific term that you know exists within a field. Because SOSL can tokenize multiple terms within a field and build a search index off this, SOSL searches are faster and can return more relevant results. Depending on the search object, SOSL searches also take advantage of the advanced features of the search index, such as out-of-order matching, synonyms, lemmatization, and spell check.
- Retrieve multiple objects and fields efficiently, and the objects might or might not be related to one another.
- Retrieve data for a particular division in an org using the divisions feature, and you want to find it in the most efficient way possible.
Define Efficient SOSL Text Searches
If your searches are too general, they are slow and return too many results. Use the following clauses to write more targeted and useful searches.
- IN: Limits the types of fields to search, including email, name, or phone.
- LIMIT: Specifies the maximum number of rows to return.
- OFFSET: Displays the search results on multiple pages.
- RETURNING: Limits the objects and fields to return.
- WITH DATA CATEGORY: Specifies the data categories to return.
- WITH DivisionFilter: Specifies the division field to return.
- WITH NETWORK: Specifies the Experience Cloud site ID to return.
- WITH PricebookId: Specifies the price book ID to return.