SAVE UP to ₹4999/- OFF On All Salesforce Courses Claim Offer

7

Dynamic SOSL | SOQL vs SOSL

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);

}
Note:

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.

SOQL vs SOSL

SOQL SOSL
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.
salesforce-developer
Next Chapter

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Book A 15-Minutes Free Career Counselling Today!