[SalesForce] Bind a List variable in a Dynamic SOQL Query

Code 1

List<String> accNameList = new List<String>{'Acc1','Acc2','Acc3'};
List<Account> accountList = Database.query('SELECT Id FROM Account WHERE Name IN:accNameList');

Code 2

List<String> accNameList = new List<String>{'Acc1','Acc2','Acc3'}
List<Account> accountList = Database.query('SELECT Id FROM Account WHERE Name IN (\''+String.join(accNameList,'\',\'')+'\')')

The two codes above are equivalent (return the same list of accounts)

Beside of using the bind list variable to prevent any flaw of SOQL Injection

Is there a performance reason (or other reason) than the one cited ?

Best Answer

Please, do the following:

  1. Open your developer console.
  2. Execute on Code 1.
  3. Under the Log tab,
  4. double click on the last execution of code 1.
  5. Debug-> View Log Panels
  6. Select Stack Tree

That will allow you to check Duration and Heap on the tab Performance Tree. This tab is on the Stack Tree panel.

Do the same for the Code 2 and compare.

Related Topic