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
Ashu sharma 38Ashu sharma 38 

Getting error too many soql

Hi,

 I am getting error too many SOQL queries.

list<lead> myLeadList=[select id,name,Ad_key__c,Advertising_Key__c from lead where Ad_key__c =null];
for(lead l:myLeadList){
 list<Lead_Vendors__c> le=[select id,Ad_key__c from Lead_Vendors__c where Ad_key__c=:l.Advertising_Key__c];
    if(le!=null && le.size()>0){
    l.Ad_key__c=le[0].id;
    update l;    
    }
    
}
 
chintal patel 25chintal patel 25
Hi Ashu Sharma,

You have to follow the best practices to avoid this type of issue.

Please refer below link.

https://developer.salesforce.com/page/Apex_Code_Best_Practices
sachinarorasfsachinarorasf
Hi Ashu,

Please use the below code to avoid too many SOQL errors.
 
list<lead> myLeadList=[select id,name,Ad_key__c,Advertising_Key__c from lead where Ad_key__c =null];
system.debug('myLeadList:::'+myLeadList);
list<Lead_Vendors__c> le=[select id,Ad_Key__c from Lead_Vendors__c ];
system.debug('le:::'+le);
list<Lead> newLead = new List<Lead>();
if(le.size()>0){
    for(lead l:myLeadList){
        system.debug('in for loop');
        for(Lead_Vendors__c lv :le){
            if(lv.Ad_key__c == l.Advertising_Key__c ){
                Lead leObj = new Lead(); 
                leObj.Ad_Key__c=le[0].id;
                leObj.Id = l.id;
                newLead.add(leObj);
            }   
        }
    }
  system.debug('newLead:::'+newLead);
  update newLead;   
}

Please read the below blog for the following point:

1. Avoid SOQL Queries or DML Statements inside ‘FOR Loops’ :
As we know how ‘For’ loop handles multiple records in bulk. When SOQL queries and DML statements are placed inside a ‘for loop’,  these are invoked for every iteration of the loop. Because of this, governor limits will be reached, so it would be best to avoid these scenarios whenever possible.

http://www.sfdcpoint.com/salesforce/salesforce-governor-limits/

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Sachin Arora
www.sachinsf.com
Ashu sharma 38Ashu sharma 38
Hi Sachin,

Thanks for helping,but its not getting an updates the lead records.
And Also i want to know why use
if(lv.Ad_key__c == l.Advertising_Key__c ){



Thanks