4

I am trying to build a query in Apex code to fetch all records where a multi select picklist has either of 2 values selected. When I build my query and string as option 1 it does not return back any data . However option 2 returns back corrent number of rows.

option1

    string str = '\'Ann-OP\',\'Ann-RP\'';

    List<Announcement__c> aL = [SELECT Id, Name FROM Announcement__c 
                                  WHERE Public_groups__c INCLUDES (:str) ];

option2

    List<Announcement__c> aL = [SELECT Id, Name FROM Announcement__c 
                                 WHERE Public_groups__c INCLUDES('Ann-OP', 'Ann-RP') ];
5

SOQL reads String str = '\'Ann-OP\',\'Ann-RP\''; as a single Picklist value rather than two Picklist values Ann-Op and Ann-RP.

Try writing a dynamic SOQL query.

Example:

List<String> includesList = new List<String>{'\'Ann-OP\'','\'Ann-RP\''};
String queryString = 'SELECT Id, Name FROM Announcement__c  WHERE Public_groups__c INCLUDES(';
for(String includeValue :includesList)
    queryString += includeValue + ',';
queryString = queryString.removeEnd(',') +')';
List<Announcement__c> aL = (List<Announcement__c>)Database.query(queryString);
| improve this answer | |
  • 3
    You could remove lines 3 - 5 and replace it with + String.join(includesList, ',') + ')';. For completeness, you could also do a ternary condition to check if the list is null. Now, I may be mistaken but, I think you can also use a dynamic binding (+ :includesList); to replace lines 3-5) in the query string you built and that should also work. – Programmable Medley Aug 7 '14 at 2:08

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.