[SalesForce] System.LimitException: Too many query rows: 50001

What I am trying to do is to set a date in my date field and also update the object. I am using the class below to do so which works just fine in my sanbox but in production I am getting this error:

System.LimitException: Too many query rows: 50001

public with sharing class updateObject{
    public  List<NRProducts__c>  values;
    public PageReference updateObject() {
        values=[SELECT Refreshed_Date__c FROM NRProducts__c ];
        for (NRProducts__c s :values){
           s.Refreshed_Date__c =Date.today();
         } 
        update values;
        return null;                  
    }    
}

VF Page:

<apex:page showheader="false" controller="updateObject" sidebar="false">
<apex:form> 
<apex:commandButton action="{!updateObject}" value="Update"/>
</apex:form>
</apex:page>

Best Answer

You're running into this on production, because you have much more data there than in your sandbox. This is a limit which is a bit harder to test against and discover in advance. You'd do well to integrate it into your salesforce developer conscious.

total number of records retrieved by SOQL queries = 50,000

You will need to use Batch Apex, in which the 50k limit counts per batch execution

These limits count for each Apex transaction. For Batch Apex, these limits are reset for each execution of a batch of records in the execute method.

This is clearly stated in the limit documentation. Salesforce enforces these rules to "force" us to use scaleable and resource friendly implementation patterns.

Related Topic