1

I was going through something, and I stumbled upon this weird behaviour.

if(true){
  String var = 'GenePoint';
}
Account acc = Database.query('Select ID,Name FROM Account where name=:var');
System.debug(acc);

If the above code snippet is executed in execute anonymous, logically it should throw an error, because the variable "var" is not in the scope, but anyway the code gets executed and the query returns the results too.

Again,

if(true){
  String var = 'GenePoint';
}
if(true){
    String var = 'Express Logistics and Transport';
}
Account acc = Database.query('Select ID,Name FROM Account where name=:var');
System.debug(acc);

If this code is executed, the query still returns the result, but this time it returns the account with the name "Express Logistics and Transport". In this case, it is considering the latest scope of variable "var".

if(true){
  String var = 'GenePoint';
} else {
  String var = 'Edge Communications';
}
Account acc = Database.query('Select ID,Name FROM Account where name=:var');
System.debug(acc);

In this case, it throws an error saying "List has no rows for assignment". Logically, considering the weird behaviour, it should have executed the body of IF block and should have taken the value of variable within the scope of it, but it is not able to take it.

I want to know whether this behaviour is valid or invalid.

  • 1
    I've linked two relevant questions to this one, please feel free to read the answers. In summary, this is invalid behavior (it is a bug), it has been logged with salesforce.com, and it may or may not be fixed at some point in the future, so you should not rely on this behavior in your code. – sfdcfox Nov 14 '19 at 17:50

Browse other questions tagged or ask your own question.