SOQL bind variable scope behavior

After I posted this question, I found a similar post that seemed to answer it: Variable scope – database.query() has access to variables not in scope. I’ll leave this in place for now, as I am not sure how to mark my own question as a duplicate

In attempting to debug a SOQL query error, I encountered a strange behavior with Database.query and bind variables. Specifically, when I run this code:

String userQuery = 'SELECT Id FROM User';
if (true) {
    List<String> firstNames = new List<String>{'James','Joe'};
    userQuery += ' WHERE FirstName IN :firstNames';
}
Database.query(userQuery);

the Database.query statement executes with no errors, despite the fact that the variable firstNames does not exist in its context. However, when I add an else clause:

String userQuery = 'SELECT Id FROM User';
if (true) {
    List<String> firstNames = new List<String>{'James','Joe'};
    userQuery += ' WHERE FirstName IN :firstNames';
} else {
    List<String> firstNames;
}
Database.query(userQuery);

I receive a null object reference exception. It seems like Salesforce is checking to see if the variable is only declared once beforehand and, if so, uses its value in the context it was declared. This seems strange to me, so I was wondering if anybody here has any insight into what is going on under the hood.

Answer

I have confirmed that this is a bug that has been logged at Salesforce, and will presumably be fixed at some point. You should not rely on this behavior, as it may break in a future version. Always make sure your variables are in scope.

Attribution
Source : Link , Question Author : Johnathan Ashley , Answer Author : sfdcfox

Leave a Comment