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
Vijaya Kumar RegantiVijaya Kumar Reganti 

How to eliminate a SOQL query from a FOR Loop inside a trigger ????

Hi Friends,

 

I have a requirement to write the following Trigger.

 

Trigger MyTrg on contact (Before insert){

 

            for (contact c : Trigger.new){

 

               list<account> lst = [Select Id,Name From Account];

   }

          

}

 

But as the SOQL query is inside the FOR loop,it hits the Governor Limit.

 

How to avoid it in a meaningful way.

 

Thanks in Advance,

 

Vijay

Best Answer chosen by Admin (Salesforce Developers) 
GunishGunish

Vijay, 

 

The rule of thumb is, if there is a query inside a for loop, then re-factor your code by using List, or Map. For e.g. in the code sample in your case, the code can be refactored as following.

 

Trigger MyTrg on contact (Before insert){
   List<Id> listOfAccoundIds = new List<Id>();
   
for(Contact eachContact : Trigger.New) {
      listOfAccountIDs.add(eachContact.AccountId);
   }

   List<Account> listOfAccounts = [select id from Account where ID IN: listOfAccountIDs];

}
          

 

Have a read of this article, as a best practise.

 

http://wiki.developerforce.com/page/Apex_Code_Best_Practices

 

-Gunish