+ Start a Discussion

System.LimitException: Too many SOQL queries: 101



I am getting an error on a trigger .


I am posting the trigger here


Can someone help me please.


trigger rollupreferred3OpenAct on Account (before insert, before update) {
    if(trigger.isinsert) {
        for( Account ac:trigger.new)
            ac.Open_Actitvities_By_Referred_3__c = 0;

    if(trigger.isupdate) { 
                 for( Account aci:trigger.new)
        for(Account ac : [select a.id, a.Referred_To_3__c, ( Select t.id from Tasks t where ( t.status != 'Completed' ) and ( t.ActivityDate >= Today ) 
        and ( t.OwnerId =: aci.Referred_To_3__c )) from Account a where a.id in :trigger.new])

     trigger.newmap.get(ac.id).Open_Actitvities_By_Referred_3__c = ac.Tasks.size();


The problem is that you have put in a query inside a for loop. You can fire as much as 100 SOQL queries. Hence the error. You need to take the query out of the for loop and use a map to access the data inside the for loop.

Can you please help me in doing that.



Sean TanSean Tan

Instead of looping through each one and executing a SOQL, you'll want to build a unique set through the loop and execute one query with an IN clause. Something like this:


Set<String> referredToKeys = new Set<String>{};

for( Account aci:trigger.new)        

for(Account ac : [select a.id, a.Referred_To_3__c, ( Select t.id from Tasks t where ( t.status != 'Completed' ) and ( t.ActivityDate >= Today ) 
			and ( t.OwnerId IN :referredToKeys )) from Account a where a.id in :trigger.new])   
	//TODO: Insert logic here

 SOQL / DML in loops should be avoided as much as possible.