bestpractice – Where does the colon (:) belong in the Apex SOQL query – to the operator or the variable?
:
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.
Read more here: Source link