Salesforce Object Search Language (SOSL) is a specialized query language designed for performing full-text searches across multiple objects and fields in Salesforce. Unlike SOQL—which is ideal for retrieving records from a single object based on defined criteria—SOSL enables you to search for keywords or partial text in several objects at once. This guide will cover everything from the basics to advanced topics, including performance considerations, governor limits, and best practices, to help you build robust search features in your Salesforce applications.

Table of Contents
1. SOSL Basics
1.1 What is SOSL?
SOSL is used to:
- Search text, email, and phone fields across multiple objects simultaneously
- Return records from various objects where the search term appears.
- Enable flexible, full-text searches similar to web search engines.
- Locate data even if you’re unsure which object holds the information
1.2 SOSL Syntax Overview | How to write SOSL query in Salesforce
The general syntax of an SOSL query is
FIND 'searchString' [IN searchGroup] [RETURNING objectTypeList]
- FIND ‘searchString’: Specifies the text string to search for. Supports wildcards (* and ?) for partial matches.
- IN searchGroup: (Optional) Defines where to search, with options such as:
ALL FIELDS, NAME FIELDS, EMAIL FIELDS, PHONE FIELDS - RETURNING objectTypeList: Lists the objects and specific fields to return.
For example:
FIND 'Acme' IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)
2. SOSL query examples for beginners Salesforce
Example 1: Basic Query
Search for the keyword “Edge” across Account and Contact objects :
FIND 'Edge' IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, FirstName, LastName, Email)
This query retrieves records from both objects where any field contains the term “Edge”.
Example 2: Using Wildcards: Asterisk
Wildcards help you search for partial matches. For instance: a search for Ram* finds items that start with Ram, such as, Rama, Raman, or Ramesh
This query returns records where any text begins with “Ram” in Account and Lead objects.
FIND 'Ram*' RETURNING Account(Id, Name), Lead(Id, Company)
Example 3: Using Wildcards: Question mark
Question marks match only one character in the middle or end of your search term. For example: a search for Ram?n finds items with the term Raman or Ramen but not Ram or Ramjan.
FIND 'Ram?n' RETURNING Account(Id, Name), Lead(Id, Company)
Example 4: Using Variables in SOSL Queries:
String searchQuery = 'Wingo OR SFDC';
List<List<SObject>> searchList = [FIND :searchQuery IN ALL FIELDS RETURNING Account(Name), Contact(FirstName, LastName)];
This Salesforce SOSL query across multiple objects, uses a variable searchQuery
to search for “Wingo” or “SFDC” across all fields in the Account
and Contact
objects and returns the names.
3. Advanced SOSL Topics
3.1 Governor Limits and Performance Considerations
Salesforce imposes limits on SOSL queries to ensure optimal performance in a multi-tenant environment. Key points include:
- Record Limit: SOSL queries can return a maximum of 2,000 records. If the search matches more than 2,000 records, only the first 2,000 are returned.
- Query Limit: You can execute up to 20 SOSL queries per Apex transaction.
- Performance: When dealing with large data volumes, limit the fields you return to those that are essential, and use search groups (e.g., NAME FIELDS) to optimize performance.
3.2 Advanced Search Group Options
Beyond ALL FIELDS, SOSL offers specialized search groups to narrow your search:
- NAME FIELDS: Searches only name-related fields.
- EMAIL FIELDS: Targets email fields.
- PHONE FIELDS: Limits search to phone numbers.
Using these options helps refine results and can improve query efficiency.
3.3 Ordering of Results
In Salesforce Object Search Language (SOSL), we can order the results using the ORDER BY
clause, similar to SOQL.
Basic Syntax
The basic syntax for ordering results in SOSL is:
FIND 'searchQuery' RETURNING object(field1, field2, ...) ORDER BY field1 [ASC|DESC]
- ASC: Ascending order (default if not specified)
- DESC: Descending order
Examples
- Order by a single field in ascending order:
FIND 'Acme' RETURNING Account(Name, CreatedDate ORDER BY CreatedDate ASC)
- Order by a single field in descending order:
FIND 'Acme' RETURNING Account(Name, CreatedDate ORDER BY CreatedDate DESC)
- Combining with Other Clauses: You can combine the
ORDER BY
clause with other clauses likeWHERE
:FIND 'Acme' RETURNING Account(Name, CreatedDate WHERE Industry = 'Technology' ORDER BY CreatedDate DESC)
- Handling Multiple Objects: Using SOSL for multi-object search in Salesforce, you can specify the order for each object separately:
FIND 'Acme' RETURNING Account(Name, CreatedDate ORDER BY CreatedDate DESC), Contact(FirstName, LastName ORDER BY LastName ASC)
3.4 Error Handling and Best Practices
When working with SOSL in Apex, consider the following best practices:
- Sanitize Input: Always escape user-supplied search strings using String.escapeSingleQuotes() to prevent errors or injection vulnerabilities.
- Exception Handling: Use try-catch blocks around SOSL queries to gracefully handle runtime exceptions.
- Selective Field Return: Only return the fields necessary for your use case to reduce processing time.
- Combining with SOQL: For scenarios requiring more complex filtering, consider running a SOSL query first to locate records and then refining the results with a SOQL query. Note that, SOSL results are returned as a list of lists in Apex. Each list within the main list corresponds to the results for each object specified in the SOSL query.
4. Implementing SOSL in Apex for efficient searches
Integrating SOSL queries within Apex allows you to build dynamic search functionality. Below is an example that demonstrates how to embed a SOSL query in an Apex class.
Example: Global search Salesforce SOSL
public class GlobalSearchHandler {
// Method to perform a SOSL search based on user input
public static void searchRecords(String searchKeyword){
// Sanitize the search string to prevent SOQL injection
String sanitizedKeyword = String.escapeSingleQuotes(searchKeyword);
// Execute the SOSL query
List<List<SObject>> searchResults = [FIND :sanitizedKeyword IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, FirstName, LastName, Email)];
// Process the results
List<Account> accountResults = (List<Account>)searchResults[0];
List<Contact> contactResults = (List<Contact>)searchResults[1];
// Debug logs for demonstration purposes
System.debug('Accounts matching: ' + accountResults);
System.debug('Contacts matching: ' + contactResults);
// Further processing can be implemented here
}
}
Explanation:
- Sanitizing Input: The searchKeyword is sanitized using String.escapeSingleQuotes() to prevent injection issues.
- Executing the Query: The SOSL query is embedded within square brackets. The query searches across all fields and returns results from the Account and Contact objects.
- Processing Results: The SOSL query returns a list of lists. Each sublist corresponds to a different sObject type, so you need to cast them to their appropriate types (Account and Contact in this case).
5. Best Practices for Using SOSL Recap
- Use Selective Filters:
- Ensure your SOSL queries are selective to avoid search crowding. Use specific search terms and targeted search groups like
NAME
,EMAIL
, andPHONE
fields - Example:
FIND 'John Doe' IN NAME FIELDS RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)
- Ensure your SOSL queries are selective to avoid search crowding. Use specific search terms and targeted search groups like
- Limit the Number of Records Returned:
- Use the
LIMIT
clause to restrict the number of records returned by your query. This helps in managing performance and avoiding timeouts - Example:
FIND 'Acme' IN ALL FIELDS RETURNING Account(Id, Name) LIMIT 100
- Use the
- Offsetting the Records Returned:
- Use the optional OFFSET to specify the starting row offset into the result set returned by your query.
- Example: if a query normally returned 50 rows, you could use OFFSET 10 in your query to skip the first 10 rows:
FIND {test} RETURNING Account(Id LIMIT 10 OFFSET 10)
- Avoid General Searches:
- General searches can be slow and return too many results. Be specific with your search terms to improve performance
- Example:
FIND 'Acme Corporation' IN ALL FIELDS RETURNING Account(Id, Name)
- Use SOSL When Appropriate:
- Use SOSL when you need to search across multiple objects or when you don’t know which object or field contains the data
- Example:
FIND 'John' IN ALL FIELDS RETURNING Account(Name), Contact(FirstName, LastName), Lead(Name)
- Optimize for Performance:
- Avoid using SOSL for searches that can be handled by SOQL, especially when searching within a single object
- Example:
// Use SOQL for single object search
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name LIKE '%Acme%'];
- Handle Large Data Volumes:
- Be mindful of the 2,000 record limit for SOSL queries. If your search terms match more than 2,000 records, consider refining your search criteria.
- Example:
FIND 'John' IN ALL FIELDS RETURNING Account(Id, Name) LIMIT 2000
- Use SOSL in Batch Apex:
- When dealing with large datasets, consider using SOSL in Batch Apex to process records in manageable chunks.
Conclusion
SOSL is an indispensable tool for Salesforce administrators and developers who need to implement robust, full-text search capabilities across multiple objects. By understanding its syntax, governor limits, advanced search options, and best practices, you can enhance your application’s search functionality significantly.
Whether you’re using SOSL in the Developer Console for quick searches or embedding it within Apex code to build global search features, mastering SOSL will help you create more dynamic and user-friendly Salesforce applications. Be sure to experiment with different search groups and optimize your queries to align with your organization’s needs. You can find additional resources here in Salesforce developer guide SOSL.
With this guide, you’re well-equipped to leverage SOSL effectively. Happy searching!