+ Start a Discussion
visual force.ax1886visual force.ax1886 

Too many SOQL's: 101 error , line16 column 1

Hi Everyone,

 

I have Quest and charge custom objects and Have look up relationship with Quest as parent. There are multiple charges on a single quest.

 

Requirement: Update the max value of discount on charge to percentage field in Quest.

 

i have the following trigger and i got Error: "Too many SOQL's: 101 error , line16 column 1" during Apex test Execution: 

 

trigger ptd on charge__c (after insert,after update, after delete) {

list<quest> quests = new list<quest__c>();
map<ID,Decimal> m = new map<ID,Decimal>();
list<aggregateResult> s = new list<aggregateResult>();
list<Charge__c> charge = new list<Charge__c>();
list<quest__c> listtobeadded=new list<quest__c>();
List<Id> Ids = new List<Id>();


for(Charge__c q:trigger.isDelete ? trigger.Old : trigger.new)
Ids.add(q.quest__c);

quests=[SELECT Percentage__c,Id,Name,(select Id,Name,Discount__c from Charge__r order by Discount__c desc limit 1) FROM quest__c where Id IN :Ids];

s=[SELECT Count(Id) total,quest__c from Charge__c Group by quest__c]; //This is line 16

for(Aggregateresult s1:s){
id i=(Id)s1.get('quest__c');
Decimal inn=(Decimal)s1.get('total');
m.put(i,inn);
}

for(quest__c qq:quotes){
if(m.get(qq.id)>0){
qq.Percentage__c=qq.Charge__r[0].Discount__c;
listtobeadded.add(qq);
}
else{
qq.Percentage__c=0;
listtobeadded.add(qq);
}
}
update listtobeadded;

}

 

 

Can you help me fix this error.

 

Thanks.

Vinita_SFDCVinita_SFDC

Hello,

 

Too many SOQL queries: 101is due to the fact, you are hitting on governor limit. The governor limit that says we can run total 100 SOQL queries in a context and you are hitting the limit.

 

It is not a good practice to query within for loop. Refer following links for best practices:

 

. http://wiki.developerforce.com/page/Best_Practice:_Avoid_SOQL_Queries_Inside_FOR_Loops

RockzzRockzz

Hi...Try below code

 

trigger ptd on charge__c (after insert,after update, after delete) {
list<quest__c> quests = new list<quest__c>([SELECT Percentage__c,Id,Name,(select Id,Name,Discount__c from Charge__r order by Discount__c desc limit 1) FROM quest__c where Id IN :Ids]);
map<ID,Decimal> m = new map<ID,Decimal>();
list<aggregateResult> s = new list<aggregateResult>([SELECT Count(Id) total,quest__c from Charge__c Group by quest__c limit 1]);
list<Charge__c> charge = new list<Charge__c>();
list<quest__c> listtobeadded=new list<quest__c>();
List<Id> Ids = new List<Id>();


for(Charge__c q:trigger.isDelete ? trigger.Old : trigger.new)
Ids.add(q.quest__c);

for(Aggregateresult s1:s){
id i=(Id)s1.get('quest__c');
Decimal inn=(Decimal)s1.get('total');
m.put(i,inn);
}

for(quest__c qq:quotes){
if(m.get(qq.id)>0){
qq.Percentage__c=qq.Charge__r[0].Discount__c;
listtobeadded.add(qq);
}
else{
qq.Percentage__c=0;
listtobeadded.add(qq);
}
}
update listtobeadded;

}