1

I would like to achieve the following using a set/list collection:

List<AccountContactRelation> accountContactRelationsList = [
            SELECT ContactId, AccountId, Roles
            FROM AccountContactRelation
            WHERE Roles INCLUDES ('finance', 'marketing')
];

I tried the following; however, it does not work

List<String> roles = new List<String>{
        'finance',
        'marketing'
};

String rolesAsString = String.join(roles, ',');
    
List<AccountContactRelation> accountContactRelationsList = [
     SELECT ContactId, AccountId, Roles
     FROM AccountContactRelation
     WHERE Roles INCLUDES :roles
];

A workaround would be to use the Database.query(); however, I prefer to use normal queries since the compiler can detect syntax errors. Do you know how to include the items of a collection in the keyword INCLUDES?

3

As per the documentation:

Bind expressions can't be used with other clauses, such as INCLUDES.

You will have to use dynamic SOQL and generate the required SOQL syntax, something like:

List<String> roles = new List<String> {
        'finance',
        'marketing'
};

String rolesAsString = '(\'' + String.join(roles, '\', \'') + '\')';
    
List<AccountContactRelation> accountContactRelationsList = Database.query(
    'SELECT ContactId, AccountId, Roles ' +
    'FROM AccountContactRelation ' +
    'WHERE Roles INCLUDES ' + rolesAsString);

Note, however, that you will need to ensure that each of the "roles" values are appropriately encoded (before being incorporated into the rolesAsString value) to prevent SOQL injection issues using String.escapeSingleQuotes.

2
  • Minor correction, the set doesn't work with String.join method, it needs list. I see this is problem in OP's code though. :)
    – Raul
    Jul 27 '20 at 10:55
  • 1
    Yeah, fixed. Ta.
    – Phil W
    Jul 27 '20 at 10:56

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.