Free Salesforce Developers Tutorials >

Chapter 7 - SOSL >

Dynamic SOSL | SOQL vs SOSL

Dynamic SOSL | SOQL vs SOSL

What You’ll Learn

S2 Labs

What Is Dynamic SOSL?

Dynamic SOSL refers to the creation of a SOSL string at run time with Apex code. Dynamic SOSL enables you to create more flexible applications. For example, you can create a search based on input from an end user, or update records with varying field names.\

How To Write Dynamic SOSL?

Use Search.query() to create a dynamic SOSL query at run time.

public static void main(String objectName)


String searchquery = 'FIND \'Edge*\'IN ALL FIELDS RETURNING Account(Id, Name), Contact, Lead'; 

List<List<SObject>> searchList = Search.query(searchquery);


Dynamic SOSL statements evaluate to a list 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. From the example above, the results from Account are first, 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 in much the same way as static SOSL queries are processed.


You know in which object the data you are searching for resides You are not sure in which object the data might be.
The data needs to be retrieved from single object or related objects. You want to retrieve multiple objects and fields, which might not be related to each other.
SOQL queries can be used in Classes and Triggers. They are only supported in Apex Classes and Anonymous blocks.
We can perform DML operations on query result. We can not perform dml operations.
It returns records. It returns fields.
You can count retrieved records. You cannot count retrieved records.


Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *