1

Can you query an object using the IN operator where the value is a variable?

This works:

stfilter = 'Kansas'
Select ID from LIcense__c where State__c IN (:stFilter)

This however doesn't work:

stfilter = ''Kansas', 'Missouri''
Select ID from LIcense__c where State__c IN (:stFilter)

BUT if I take the same thing and just put it in the query it does work:

Select ID from LIcense__c where State__c IN ('Kansas','Missouri')

Do I need to transform the string somehow first?

3 Answers 3

6

You can simply bind a Listor Set of any type. For example:

List<String> stFilterList = new List<String>();
stFilterList.add('Kansas');
stFilterList.add('Missouri');

// Query would be like
Select ID 
FROM LIcense__c 
WHERE State__c IN : stFilterList
2

Yes, You can create list or set of values and refer that List or Set in the SOQL, Simple!

For List : 
stFilter= new List<string>();
stFilter.add('Iteam1');
stFilter.add('Iteam2');

For Set:
stFilter= new Set<string>();
stFilter.add('Iteam1');
stFilter.add('Iteam2');

Select ID from LIcense__c where State__c IN :stFilter;

If this helped you, Please mark it as best answer!

Thanks.

0

Yes, as answered by others, you need to put them into a list.

You can further improve if required to use LIKE also to be used along with IN for a list.

setAccNames.add('%'+'ABC'+'%');
setAccNames.add('%'+'XYZ'+'%');
setAccNames.add('%'+'RST'+'%');

List<Account> accList = [SELECT Id FROM Account WHERE Name LIKE :setAccNames];

More on this --> https://sfdcfanboy.wordpress.com/2016/03/01/use-like-and-in-in-a-single-soql-query/

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.