Search code examples
salesforceapexsoql

Salesforce, Apex, SOQL, SELECT with INCLUDES


What is wrong at this code in Apex?

String states = 'California,New York';
List<Account> lstACC = [SELECT Id, Name, BillingState FROM Account WHERE BillingState INCLUDES (:states) LIMIT 10];

In Developer Console is an Error: "BillingState FROM Account WHERE BillingState INCLUDES (:states)^ERROR at Row:1:Column:50 includes or excludes operator only valid on multipicklist field".


Solution

  • The right solution:

    Set<String> setStates = new Set<String>();
    setStates.add('California');
    setStates.add('New York');
    List<Account> lstACC = [SELECT Id, Name, BillingState 
                            FROM Account 
                            WHERE BillingState IN :setStates 
                            LIMIT 10];
    

    Wrong:

    setStates: {'California','New York'}
    

    Right:

    setStates: {California,New York}
    

    Apostrophes are in addition. OR

    String states = 'California,New York';
    List<String> listStates = states.split(',');
    List<Account> lstACC = [SELECT Id, Name, BillingState 
                            FROM Account 
                            WHERE BillingState IN :listStates 
                            LIMIT 10];
    

    Wrong:

    String states = '\'California\',\'New York\'';
    

    Right:

    String states = 'California,New York';
    

    SOQL injection is in addition.