3

How does = differ from =: ?

My code snippet below only works when using =:, however when looking through the SOQL documentation, I mostly see examples using =.

public class AccountUtils {

    public static List<Account> accountsByState(String abbr) {
        list<Account> result = [SELECT ID, Name FROM Account WHERE BillingState =: abbr];
        system.debug(result);
        return result; 
    }
}

Versus an example from the documentation that uses =:

SELECT Id
FROM Case
WHERE Contact.LastName = null
1

2 Answers 2

6

The : denotes a variable, in your case for abbr in your SOQL e.g.

SELECT ID, Name FROM Account WHERE BillingState = :abbr

as opposed to null which is a literal value

SELECT Id FROM Case WHERE Contact.LastName = null

in short if you are using a variable in SOQL then use : before the variable name.

4
  • 5
    Put in a slightly different way, there is no =: operator in SOQL, the equality "=" and bind ":" operators are two separate things.
    – Derek F
    Aug 25, 2020 at 0:03
  • 4
    : denotes a variable or expression. This bit is important. You can do, for example, :System.today().addDays(5) if you wanted to, or even :Math.getRandomLong(). Dynamic queries only support variables, but inline queries support both variables and expressions.
    – sfdcfox
    Aug 25, 2020 at 2:46
  • This makes sense, and thank you for the clarification on the bind operator! Aug 26, 2020 at 3:22
  • Because they are two different operators, it should be preferred that there is a space between the two, and that the bind operator touch the expression it is bound too: WHERE Id IN :someSet. This helps eliminate ambiguity in what the two operators are doing and makes it clear that, unlike the addition assignment operator += or the less than or equal to operator <=, putting the two of them together does not make them work any differently.
    – nbrown
    Sep 23, 2020 at 13:08
2

SOQL and SOSL statements in Apex can reference Apex code variables and expressions if they’re preceded by a colon (:). This use of a local code variable within a SOQL or SOSL statement is called a bind. The Apex parser first evaluates the local variable in code context before executing the SOQL or SOSL statement. Bind expressions can be used as:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_variables.htm#!

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.