1

I'm asking about a best practice - Salesforce gives us freedom here but we'd like to establish some sort of consistency in our team. Similar to the case size - although Apex is case-insensitive, it's recommended to write it with having camelCase in mind for variables/methods and PascalCase for classes.

So in Apex code that uses an SOQL query with a variable as a filter, where should the colon belong - to the operator or the variable?

[SELECT Id FROM Account WHERE Name = :variable]

or

[SELECT Id FROM Account WHERE Name =: variable]

3 Answers 3

8

: is the binding operator. It behaves differently depending on if you're using inline SOQL/SOSL or dynamic SOQL/SOSL.

With inline queries, : starts a section of Apex Code execution within the query. It may or may not have white space on either side. The following three queries are identical:

SELECT Id FROM Account WHERE Name = :accountName
SELECT Id FROM Account WHERE Name = : accountName
SELECT Id FROM Account WHERE Name =:accountName

Since : can be code, you can even:

SELECT Id FROM Account WHERE Name = :getAccountName()

In Dynamic SOQL/SOSL, the rules are different. The : cannot have a space after it, and what follows must be a variable name, not any kind of Apex Code.

Valid:

SELECT Id FROM Account WHERE Name = :accountName

Invalid:

SELECT Id FROM Account WHERE Name = : accountName
SELECT Id FROM Account WHERE Name = :getAccountName()
SELECT Id FROM Account WHERE Name = :accountNames[0]
SELECT Id FROM Account WHERE Name = :accountsVar.someProp

As far as which side should "own" the colon, it must be the variable. This provides a consistent reading experience, especially when you start using dynamic queries, as it is already required.

Most developers also strongly prefer that operators have spaces on either side, so = "owns" the space on either side of it, which is why we wouldn't ordinarily write Name=:accountName. The : has nothing to do with this formatting style, it's the operator that demands some space.

5

From a practical standpoint, either works. While SOQL does have some syntactically significant whitespace (e.g. between filters in the WHERE clause, between the last field in the SELECT clause and the start of the FROM clause), it doesn't matter here. Even Name=:variable would work.

Personally, I prefer the Name = :variable approach, because the piece in the middle of that expression is an operator, and =:, <:, >=:, etc... aren't SOQL/SOSL operators.

2

To the variable, because it is not part of the operator.

And I like to consider it as some sort of modifier/pointer to make that variable work with the query.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .