3

The below apex code returns same result when used in controller/trigger, then what is the advantage of having bind(:) variable in static query?

List<Account> lstAccount1 = [Select id, Name from Account where Name =:'Testing Acc' limit 10];

List<Account> lstAccount2 = [Select id, Name from Account where Name = 'Testing Acc' limit 10];

system.debug(lstAccount1);
system.debug(lstAccount2);

Thanks in advance :)

4

You use : when you're actually binding a variable:

String myString = 'Testing Account'; List<Account> lstAccount1 = [Select id, Name from Account where Name =:myString limit 10];

This is useful in cases where you don't know the value of your variable, for an example you call another method to calculate something and then you want to bind the result directly in the query:

String myString = SomeClass.findAccountName(); List<Account> lstAccount1 = [Select id, Name from Account where Name =:myString limit 10];

Also it can be useful when you have some conditional statements which can change the same variable which is ultimately used in a SOQL:

String accountName = '';

if (value == true)
{
    accountName = 'Something';
}
else
{
    accountName = 'Something Else';
}

List<Account> lstAccount1 = [Select id, Name from Account where Name =:accountName limit 10];

And so forth...

Hope that makes things more clear.

0
3

There's no benefit in your use case; in fact, the dynamic binding (':') has slightly worse performance. You should only bind to variables. The advantage is when you want to use a variable:

List<Account> lstAccount1 = [Select id, Name from Account where Name =:userInput limit 10];

While you can use either for a normal string, binding causes Apex Code to be executed, slightly causing worse performance.

0

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.