function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
@login.ax974@login.ax974 

SOQL optimization guidelines

Hi,

 

 I want to ask one very basic question here - suppose my code is like this:

 

Set<Id> stAcctId = new Set<Id>();
for Account a : trigger.new)
{
   if (a.OwnerId != trigger.oldMap.get(a.id).OwnerId)
      {
         stAcctId.add(a.Id);
      }
}

List<Contact> lstContacts = [SELECT Id, Ownership_Changed__c FROM Contact WHERE AccountId IN :stAcctId AND Contact_Type__c = 'New User'];

 

Even if my collection stAcctId is empty, will the SOQL fire? If yes, will it be counted in the total number of SOQL queries?

Is checking before firing the query whether or not the collection is empty a good practise?

 

Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
Abhinav GuptaAbhinav Gupta

You should check the collection being empty before firing the query, and yes the query will fire for once.