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

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 :{

        for(Opportunity o : trigger.old){

            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){
            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){

                    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.TotalAmount__c = PaymentSum;
                        d.TotalOpportunityQuantity__c= Quantity;
    update dealsToUpdate;
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 will run into the same limitation using @future.
Came across the below post which might help you as well
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.