Create Dynamic SOSL Query in Salesforce Apex (Complete Guide with Examples)
Dynamic SOSL in Salesforce Apex allows developers to build flexible search queries at runtime, enabling searches across multiple objects and fields based on user inputs or changing conditions. This approach is especially valuable for efficiently searching large datasets across multiple Salesforce objects like Account and Contact. The article provides clear syntax, example code, and execution guidance, showing how to use the Search.query() method dynamically. Salesforce teams can apply this to create highly customizable search functionality that adapts to runtime requirements without hardcoding queries.
- Use Search.query() to execute dynamic SOSL queries in Apex at runtime.
- Construct SOSL query strings dynamically based on user input or conditions.
- Dynamic SOSL returns a List<List<sObject>> with ordered results per object.
- Iterate over each sObject list to process results for different Salesforce objects.
- Dynamic SOSL is faster than SOQL for text searches across multiple objects.
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.