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
FinneyFinney 

System.LimitException: Too many SOQL queries: 101

Hi,

 

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;
    }
    

else
    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();
   

     }
  }

raseshtcsraseshtcs
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.
FinneyFinney

Can you please help me in doing that.

 

Thanks

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)        
{
	referredToKeys.add(aci.Referred_To_3__c);		
}

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.