[SalesForce] Too many query rows 50001

Can anyone please tell me if there is something wrong with the scrip below. I am using LIMIT 50000 but still getting this error. I will appreciate any help!

code:

    //for mws chart
  AggregateResult[] groupedSales 
  =[SELECT CALENDAR_MONTH(Purchase_Date__c),CALENDAR_YEAR(Purchase_Date__c), SUM(Detail_Total__c)
   FROM MWSOrderItem__c 
   WHERE  Purchase_Date__c = LAST_N_DAYS:365 AND Buyer_lookup__c =:UserInfo.getUserId()
   GROUP BY CALENDAR_MONTH(Purchase_Date__c),CALENDAR_YEAR(Purchase_Date__c)
   ORDER BY CALENDAR_YEAR(Purchase_Date__c),CALENDAR_MONTH(Purchase_Date__c) ASC LIMIT 50000 ];

  List1 = new List<String>();  

 for (AggregateResult ar11 : groupedSales )  {

   List1.add(String.valueof(ar11.get('expr0')+'/'+String.valueof(ar11.get('expr1'))));
   List1.add(String.valueof(ar11.get('expr2')));

 } 

Best Answer

The Limit in your query does not apply on the Total number of rows which were accessed but on the number of AggregatedRows returned. Thus if 1 of your Aggregated Rows has touched more than 1 rows you hit the limit...

This is implied in the documentation: Working with SOQL Aggregate Functions

Queries that include aggregate functions are subject to the same governor limits as other SOQL queries for the total number of records returned. This limit includes any records included in the aggregation, not just the number of rows returned by the query. If you encounter this limit, you should add a condition to the WHERE clause to reduce the amount of records processed by the query.

but it's not 100% clear ;-)

Related Topic