+ Start a Discussion
Radhika MRadhika M 

Batch failed Due to: too many query rows 50001

​Hi All,
I have a schedule class which invokes the batch class to insert / update records.
Due to this DML operations another apex class is getting called by Trigger.
In this apex class I have soql query (which is doing some aggregations) hitting the governor limit.
In debug log the aggregation query is returning 2270 rows, but salesforce is throwing an exception like System.LimitException: Too many query rows: 50001
My log is below
09:55:21.430 (42430723507)|SOQL_EXECUTE_BEGIN|[550]|Aggregations:0|SELECT SUM(Total__c) totalAmt, SUM(Total_Lifts__c) totalLifts, Service__c serviceId, Invoice_Start_Date_New__c invStartDate, Invoice_End_Date_New__c invEndDate FROM Purchase_Invoice_Line_Item__c WHERE (Service__c = :tmpVar1 AND Total__c != NULL AND Invoice_Date__c != NULL AND Invoice_Start_Date_New__c != NULL AND Invoice_End_Date_New__c != NULL) GROUP BY Service__c, Invoice_Start_Date_New__c, Invoice_End_Date_New__c
09:55:21.766 (42766218603)|SOQL_EXECUTE_END|[550]|Rows:2270
09:55:21.766 (42766286835)|EXCEPTION_THROWN|[550]|System.LimitException: Too many query rows: 50001
09:55:21.766 (42766462757)|METHOD_EXIT|[11]|01pw0000000FM3g|TGH_ILI_Helper.createInvoicePurchaseLineItem(List<Purchase_Invoice_Line_Item__c>, Boolean)
09:55:21.766 (42766563397)|FATAL_ERROR|System.LimitException: Too many query rows: 50001
Hope someone can help me to overcome this limit exception
Deepu BDeepu B
That your SOQL query retrieving more than 50000 records in your batch apex, 
take records in list and proceed.
Himanshu ParasharHimanshu Parashar
Hi Radhika,

Add Limit to your batch class SOQL.
Karthik TrainingKarthik Training
Hi Radhika,

 Please check whether you are writing this SOQl in side the for loop?

Radhika MRadhika M
Hi all, Thanks for your quick reply..!
The soql query exists in general apex class (not in batch class) and it’s not in inside the for loop. I couldn’t even put the limit because here I am calculating total amount of all invoice line items by using aggregate function.

The query is like below:
      List<AggregateResult> ILITotalList;
            // Get the sum of all the line items
                if(serviceIdSet != null && (!serviceIdSet.isEmpty()))
                    ILITotalList = [SELECT SUM(Total__c) totalAmt, SUM(Total_Lifts__c) totalLifts, Service__c serviceId, Invoice_Start_Date_New__c                                    invStartDate,Invoice_End_Date_New__c invEndDate FROM Purchase_Invoice_Line_Item__c 
                                   WHERE Service__c IN :serviceIdSet
                                   AND Total__c != null AND Invoice_Date__c != null AND Invoice_Start_Date_New__c != null AND Invoice_End_Date_New__c != null
                                   GROUP BY Service__c, Invoice_Start_Date_New__c, Invoice_End_Date_New__c];
            } catch (Exception ex) {
                System.debug('&&&Exception Occured'+ex);