7

I need to query for an object based on 2 string variables. The first one is a constant but the second one gets passed to the class constructor.

So in the end I want to achieve something like this:

public class MyClass {
    private final String STRING_ONE = 'STRING ONE';

    public MyClass(String stringTwo) {
        List<Object__c> objects = [
           SELECT Id
           FROM Object__c
           WHERE Name IN :{STRING_ONE, stringTwo}
        ];
    }
}

This is the part that I can't get the syntax right of WHERE Name IN :{STRING_ONE, stringTwo}. I know I've seen this somewhere but can't find it on google.

6

It's like normal SOQL, but you put the colons before each item in the list:

public class MyClass {
    private final String STRING_ONE = 'STRING ONE';

    public MyClass(String stringTwo) {
        List<Object__c> objects = [
           SELECT Id
           FROM Object__c
           WHERE Name IN (:STRING_ONE, :stringTwo)
        ];
    }
}
  • Thank you, that's what I was looking for! – Arthlete Mar 15 at 22:14
  • 1
    @Arthlete You're welcome! I know it's pretty unusual syntax, so glad you asked so people could find the answer to this. – sfdcfox Mar 15 at 22:18
9

You can supply string variable values using Apex binding. When you're not using Dynamic SOQL, as you're not here, you can even use complex Apex expressions in the bind. The following options are all legit.

... WHERE Name IN (:STRING_ONE, :stringTwo)

... WHERE Name IN :new List<String>{STRING_ONE, stringTwo}

... WHERE Name = :STRING_ONE OR Name = :stringTwo

List<String> names = new List<String>{STRING_ONE, stringTwo};
[SELECT ... FROM Account WHERE Name IN :names]

Dynamic SOQL doesn't allow complex bind expressions, so creating new Lists and similar are verboten in that context.

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.