+ Start a Discussion
max.alexander1.3945796734965325E12max.alexander1.3945796734965325E12 

Error Message System.LimitException: Too many query rows: 50001

I have this piece of code that does roll up summary on relatd object for Opportunity called deal__c, however i get this error and i'm not sure why.
here is my code   Trigger.Deals: line 59, column 1, is there any way to overcome it by writing beter querry? or do ihave to create batch class? or put it @ future?

set<id> DealIds = new set<id>(); //roll up summary
    if((trigger.isInsert || trigger.isUpdate) && Trigger.isAfter){
        for(Opportunity o : trigger.new){
            DealIds.add(o.Deal__c);
        }
    }

    if(trigger.isDelete){
        for(Opportunity o : trigger.old){
            DealIds.add(o.Deal__c);
        }
    }

            map<id, Decimal> DealAmountMap = new map<id, Decimal>();
            List<AggregateResult> oList =[select Deal__c,sum(Amount) from Opportunity where Deal__c IN :DealIds group by Deal__c];
            for(AggregateResult q : oList){
                DealAmountMap.put((Id)q.get('Deal__c'),(Double)q.get('expr0'));
            }
   
            map<id, Decimal> DealQuantityMap = new map<id, Decimal>();
            List<AggregateResult> oList1 =[select Deal__c,sum(TotalOpportunityQuantity) from Opportunity where Deal__c IN :DealIds group by Deal__c];
            for(AggregateResult q1 : oList1){
                DealQuantityMap.put((Id)q1.get('Deal__c'),(Double)q1.get('expr0'));
            }

                    list<Deal__c> dealsToUpdate = new list<Deal__c>();
                    List<Deal__c> Deals=[Select Id, TotalAmount__c from Deal__c where Id IN :DealIds];
                    for(Deal__c d : Deals){
                        Double PaymentSum = DealAmountMap.get(d.Id);
                        Double Quantity = DealQuantityMap.get(d.id);
                        d.TotalAmount__c = PaymentSum;
                        d.TotalOpportunityQuantity__c= Quantity;
                        dealsToUpdate.add(d);
                    }
    update dealsToUpdate;
VictorFelisbinoVictorFelisbino
The only way you will be able to do this would be in a batch job, which can be scheduled to run on a schedule.

Salesforce has a limit that a soql cannot return more than 50000 records even though you are using a aggregateResult, it still counts all the rows to return your result.

You could set your trigger to run the batch job, but that can get very messy...you will run into the same limitation using @future.
Ramu_SFDCRamu_SFDC
Came across the below post which might help you as well

https://developer.salesforce.com/forums?id=906F000000091sVIAQ
praveen murugesanpraveen murugesan
Hi Alex,

You cant query more than 50000 records. For this you may use limit 50000.

Else you can use batch job with @future method.

Thanks.