Is there any way to convert SOSL Find clause into SOQL where clause ? For example following SOSL and SOQL both have same filter criteria.

SOSL: FIND {'ABC' and 'XYZ'} IN ALL FIELDS Returning ACCOUNT(fieldList)

SOQL: Select fields from Account where (Name ='ABC' and Name = 'XYZ')

I have a situation where I come to know at run time, which field to search, hence some time SOSL and some time SOQL will fit into my requirement. But problem is that While providing input, user can input searchText which can have 'operators/phrases' from UI which will directly fit into FIND clause of SOSL, whereas we need to convert that searchText into Where clause to fire SOQL properly.

Hence looking for a way to convert FIND clause into SOQL where clause.

Thanks in Advance.


Perhaps you can explain why you can't just execute the SOSL; why do you need to convert it into SOQL?

If you do need to use SOQL sometimes, it sounds like your Apex code will have to start by parsing the user's input to identify the tokens used and then decide whether to execute Dynamic SOSL or Dynamic SOQL.

The documentation for SOSL's FIND term is several pages long. Parsing something that complicated and then mapping it to roughly equivalent SOQL would be a lot of work and require a lot of tests to be written.

But as you are in control, it is up to you how much of SOSL's syntax you allow your users access to use. So I suggest you create your own "mini-language" (simpler than FIND) for the allowed user input that supports the main things you know your users need to do. That should allow you to write simpler code and fewer tests.

(Or you might provide UI somewhat like Salesforce's view filtering to make it easier for your users to create their queries. That avoids the parsing part of the problem: you just create the Dynamic SOSL or Dynamic SOQL based on the selections.)

Take care to guard against SOQL injection.

  • The reason for firing SOQL instead of SOSL sometimes is that, I am providing UI where User can select certain field to search the phrase. Hence need SOQL. and If user dosn't select any field to search then SOSL search will be fired. Apr 7 '14 at 14:14
  • @user3237545 Makes sense.
    – Keith C
    Apr 7 '14 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.