Create Dynamic SOSL Query in Salesforce Apex (Complete Guide with Examples)

In Salesforce Apex, searching data efficiently is very important, especially when working with large datasets. Salesforce provides two main query languages: SOQL and SOSL.

While SOQL is used to query specific objects, SOSL (Salesforce Object Search Language) is used to search across multiple objects and fields at once.

Static SOSL queries are predefined: we write the query and execute it. However, the dynamic SOSL queries enable developers to construct search queries dynamically at runtime based on user input or varying conditions.

In this tutorial, we will learn about what dynamic SOSL is, its syntax, how to use dynamic SOSL queries in Salesforce Apex using examples, and how to execute them in Apex.

What is a Dynamic SOSL Query in Salesforce Apex?

A Dynamic SOSL is a query string that is constructed at runtime rather than being hardcoded. This provides flexibility for fetching data based on user preferences or dynamically changing conditions.

Syntax:

List<List<sObject>> searchResults = [ FIND 'Text' IN ALL FIELDS RETURNING Object Name ( Field1, Field2 ), Object Name (  Field1, Field2 )];
  • List<List<sObject>>: The dynamic SOSL queries return a list of lists. Each inner list contains records from a specific object type.
  • FIND ‘Text’: Searches for the provided keyword in the specified fields. It is case-insensitive and finds matches in text-based fields.
  • Object Name-> The objects to search, standard or custom objects (e.g., Contact, Account, Lead).
  • Fields: The specific fields to return.

Example of a Dynamic SOSL Query

String searchText = 'John';
String dynamicQuery = 'FIND '' + searchText + '' IN ALL FIELDS RETURNING 
                                                                  Account(Name), Contact(FirstName, LastName)';
List<List<sObject>> searchResults = search.query(dynamicQuery);

In the above example, we declared a string to hold the search text we want to retrieve from objects.

After that, we declared another string to hold the SOSL query, and we provided the search text in that query.

Using these strings, we can modify the query at runtime, so we don’t need to edit the search text in the Apex-created query.

Dynamic SOSL statements evaluate alist of lists of sObjects, where each list contains the search results for a particular sObject type.

The result lists are always returned in the same order as they were specified in the dynamic SOSL query. In the example above, the results are: Account, then Contact, then Lead.

The Search.query() method can be used wherever an inline SOSL query can be used, such as in regular assignment statements and for loops. The results are processed much the same way as static SOSL queries.

SOQL vs SOSL in Salesforce

FeatureSOQLSOSL
Search TypeSpecificGlobal
ObjectsOne objectMultiple objects
Use CaseStructured dataText search
SpeedSlower for searchFaster

How to Create Dynamic SOSL Query in Salesforce

In the example below, I will explain how to create a dynamic SOSL in Apex so users can construct search queries at runtime based on input or varying conditions.

To create a dynamic search query to retrieve data at runtime from the Salesforce org, we need to use the Search.query() method in Apex.

To build a dynamic SOSL query, we need to follow the following steps:

  • Define the search term dynamically based on user input.
  • Construct the SOSL query as a string.
  • Use the Database.query() method to execute the query.

Now, let’s create a class to implement the SOSL query and display the retrieved data using the search query method.

public class DynamicSOSL {
    public static List<List<sObject>> searchRecords(String searchTerm) {
                
        String dynamicQuery = 'FIND \'' + searchTerm + '\' IN ALL FIELDS RETURNING ' + 
                      'Account(Id, Name), Contact(Id, FirstName, LastName)';
        
        List<List<sObject>> searchResults = search.query(dynamicQuery);
        return searchResults;
    }
}

First, we created an Apex class with a static method that returns a List<List<sObject>>, where each list contains sObjects (records) from different objects.

Then, the searchRecords(String searchTerm) method takes a search term (String) as input from the user at run time.

After that, we created a String variable to store the SOSL query. In the SOSL, we created a query as FIND ‘searchTerm‘ IN ALL FIELDS from an account and contact object with the provided fields.

Finally, we need to use Search.query(dynamicQuery) method to execute the SOSL query dynamically, and we also passed a string variable where we stored the search query.

Now, we have multiple objects from which we retrieved records, and to store those records in separate lists, we declared an array of lists in Apex.

It returns a list of lists where:

  • searchResults[0]: List of account records.
  • searchResults[1]: List of contact records.

After that, as we declared the method as static, we need to return the search results as a list of lists.

Execute the Apex Code:

Now, let’s execute the apex class. For that, open the anonymous window and provide the search text.

List<List<sObject>> results = DynamicSOSL.searchRecords('oil');
System.debug ('===== SEARCH RESULTS =====');

  if (results.isEmpty()) {
          System.debug('No records found.');
     } else {
 
   if (!results[0].isEmpty()) {
          System.debug('--- Accounts ---');
                for (sObject acc : results[0]) {
                       Account a = (Account) acc;
                       System.debug('Id: ' + a.Id + ' | Name: ' + a.Name);
                 }
      }

    if (!results[1].isEmpty()) {
          System.debug('--- Contacts ---');
                for (sObject con : results[1]) {
                      Contact c = (Contact) con;
                      System.debug('Id: ' + c.Id + ' | First Name: ' + c.FirstName + ' | Last Name: ' + 
                                                             c.LastName);
               }
       }
}

Here, we declared a list of lists to store the results of the SOSL query. Then, using DynamicSOSL.searchRecords(‘oil’), we called the static method and passed the text we wanted to search for in the Salesforce data across all searchable fields of the Account and Contact objects.

After that, using an if statement first, we checked the list to see whether it contained records.

If it includes records, to display records for different objects, we need to use if statements and a for loop to iterate over the documents.

Then, using the debug method, we displayed the list collection variable that stores the retrieved data. In the image below, you can see the search result.

As a result, if you look carefully at the account records, you will see that we have the ‘oil’ text we were searching for.

But in the contact record, we don’t have that searched text even though contacts are displayed; why did this happen? Because in the SOSL query, the text we searched was across all the fields in the Salesforce org.

Dynamic SOSL Query in Salesforce Apex

In the image below, you can see that the account name in the contact record contains the searched text (oil), which is why it is displayed in the search results.

Create Dynamic SOSL in Salesforce

In this way, we can create dynamic SOSL queries in Salesforce Apex to construct search queries dynamically at runtime based on user input or varying conditions.

Frequently Asked Questions

Q1: What is Dynamic SOSL?

Creating an SOSL query at runtime

Why use SOSL?

For fast search across multiple objects

What does SOSL return?

List of lists of SObjects

Is SOSL faster than SOQL?

Yes, for text search

Conclusion

Dynamic SOSL Query in Salesforce Apex is a powerful feature that enables developers to build flexible, efficient search functionality. It is especially useful when search terms and objects are not fixed.

I hope you have an idea of what dynamic SOSL is and how to use a dynamic SOSL query in Salesforce Apex, with examples. In that, I have explained dynamic SOSL syntax, an example, and how to execute it in Apex.

By understanding its syntax, use cases, and best practices, you can build scalable and secure search features in your Salesforce applications.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.