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
SoCal AdminSoCal Admin 

SOQL Limit Exception / Too Many Queries

 

I received the following exception message after I moved the following code to production:

       System.LimitException: Too many SOQL queries: 101

 

I want to compare a value in the current record being saved against the top 5 values in the accounts table.  I should only be running ONE query per update - but somehow it's running a lot more.

 

It works fine when *testing* DEV and PRODUCTION, so I think some periodic process in Salesforce is sending a *batch* of records to the trigger instead of just one and it appears to be a lot of records at once.  Additionally, I only want the SOQL query to run if the user types a '?' in the custom field..

 

Anyone have any suggestions?  Perhaps if I move the SELECT statement into the IF statement.  I'm very familiar with queries in general - just not familiar with Apex syntax.

 

 

public static void checknumber(Account[] rur) {

 

for(Account m:rur) {
            

              Account[] acc = [Select inbr__c from Account where inbr__c > 35000 order by inbr__c desc limit 5

 

             if (myfield == '? ') {

                   //do_stuff_here

            }

 

}

 

Best Answer chosen by Admin (Salesforce Developers) 
Ritesh AswaneyRitesh Aswaney

Never a good idea to execute a SOQL query inside a For Loop

 

Perform the query before entering the for loop, and then merely compare

 

so

  Account[] acc = [Select inbr__c from Account where inbr__c > 35000 order by inbr__c desc limit 5];

 

for( Account m : rur){

  for(Acc innerAcc : acc){

  if (myfield == '? ') {

                   //do_stuff_here

            }

 }

 

}

 

All Answers

Ritesh AswaneyRitesh Aswaney

Never a good idea to execute a SOQL query inside a For Loop

 

Perform the query before entering the for loop, and then merely compare

 

so

  Account[] acc = [Select inbr__c from Account where inbr__c > 35000 order by inbr__c desc limit 5];

 

for( Account m : rur){

  for(Acc innerAcc : acc){

  if (myfield == '? ') {

                   //do_stuff_here

            }

 }

 

}

 

This was selected as the best answer
SoCal AdminSoCal Admin

 

Yes - I was aware of that - but I wasn't aware that the records in 'm' was the entire Account recordset.  I thought the trigger passed the record being updated ( = 1 record)

 

Thanks for your help.