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
Ramya BalakrishnanRamya Balakrishnan 

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

Hi all  
I have the following class which is called in Flow action when creating events. I am getting the following error when i try to create event.

We can't save this record because the “Type” process failed. Give your Salesforce admin these details. An Apex error occurred: System.LimitException: Too many query rows: 50001 Error ID: 563784318-263669 (-505665031)ccurred: System.LimitException: Too many query rows: 50001 Error ID: 563784318-263669 (-505665031)


The class


public class UpdateNo_ofInterviewsWithTotalActivities {

    // Do not remove this variable as this is used in the trigger to avoid loop
    public static Boolean isUpdatingNumberOfInterviews = false;

  
    /* @description : This method updates opportunity's Number_of_Interviews__c field based on the
    * opportunity's Event subject
    * @param : events list of Event derived from Process builder
    */
    @InvocableMethod public static void updateOppField(List<Event> events) {
        try {
            Set<Id> oppIdsRelatedToEvents = new Set<Id>();

            for (Event evnt : events) {
                String sub = evnt.Subject;
                if (sub != null && (sub.containsIgnoreCase('Interview') || sub.containsIgnoreCase('intvw') || sub.containsIgnoreCase('screen'))) {
                    System.debug('Event Subject is: ' + sub);
                    if (evnt.WhatId != null || evnt.WhatId != '') {
                        oppIdsRelatedToEvents.add(evnt.WhatId);
                    }
                }
            }
            System.debug('oppIdsRelatedToEvents' + oppIdsRelatedToEvents);

            List<Opportunity> oppsList = [SELECT Id, Name, Number_of_Interviews__c FROM Opportunity WHERE Id In:oppIdsRelatedToEvents];
            System.debug('Opportunities with the Event subjects that contains Interview : ' + oppsList);

            List<Event> eventsList = [SELECT Id, WhatId, Subject FROM Event WHERE WhatId In:oppIdsRelatedToEvents];
            System.debug('Events that are related to Opportunities : ' + eventsList);

            Map<Id, Set<Id>> eventOppsMap = new Map<Id, Set<Id>>();
            if (eventsList != null) {
                for (Event e : eventsList) {
                    if (e != null && e.WhatId != null) {
                        String sub = e.Subject;
                        if (sub != null && sub.containsIgnoreCase('Interview') || sub.containsIgnoreCase('intvw') || sub.containsIgnoreCase('screen')) {
                            if (!eventOppsMap.containsKey(e.WhatId)) {
                                Set<Id> eventsIds = new Set<Id>();
                                eventsIds.add(e.Id);
                                eventOppsMap.put(e.WhatId, eventsIds);
                            } else {
                                Set<Id> eventsIds = eventOppsMap.get(e.WhatId);
                                eventsIds.add(e.Id);
                            }
                        }
                    }
                }
            }
            System.debug('Events with Opps map : ' + eventOppsMap);
            List<Opportunity> oppsTobeUpdated = new List<Opportunity>();
            if (oppsList != null) {
                for (Opportunity opp : oppsList) {
                    Set<Id> oppEventIds = eventOppsMap.get(opp.Id);
                    // Do not remove this variable as this is used in the trigger to avoid loop
                    if (oppEventIds.size() > 0)
                        isUpdatingNumberOfInterviews = true;
                    opp.Number_of_Interviews__c = oppEventIds.size();
                    System.debug('Number of Interviews : ' + opp.Number_of_Interviews__c);
                    oppsTobeUpdated.add(opp);
                }
                try {
                    update oppsTobeUpdated;
                }
                catch(DmlException dmle) {
                    System.debug(dmle);
                    System.debug(dmle.getMessage());
                    DBUtils dbUtil = new DBUtils();
                    dbUtil.handleException('Updating opportunities in process builder', dmle.getMessage(), dmle.getLineNumber());
                }
                System.debug('Opps to be updated in the Update No.of Activities class are : ' + oppsTobeUpdated);
            }
        }
        catch(Exception e) {
            system.debug(e);
            system.debug('Exception occurred when updating the events : ' + e.getMessage());
        }
    }
}


In sandbox it is working. In production we are getting this error. Do I need to use Batch Apex? How to implement batch apex in this?
AnkaiahAnkaiah (Salesforce Developers) 
Hi Ramya,

Can you explain the scenario?

Thanks!!
mukesh guptamukesh gupta
Hi Ramya,
  1. SOQL calls should be filtered. They should have a WHERE clause and LIMIT which could prevent this exception.
  2. Check rows returning from all SOQL queries in the transaction, not in a single SOQL query.
  3. Use these debug statements to check query rows governor limit of your org and the rows queried so far in your code-System.debug(‘Total number of records retrieved by SOQL queries:’+Limits.getLimitDmlRows());System.debug(‘Number of records retrieved by SOQL queries so far: ‘ + Limits.getDmlRows());
  4. One most important thing that everyone misses out on is Aggregate queries thinking, it is returning only the aggregate rows but queries with aggregate functions count each row used by the aggregation(as a query row) for limit tracking.
if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
Ramya BalakrishnanRamya Balakrishnan
Hi Thanks for your response. But here in my scenario , I want all the rows from the Event object.So I am not filtering the query. The following query returns more than 5000 rows so the governor limit exceeds. Event object has around 8000 records. List eventsList = [SELECT Id, WhatId, Subject FROM Event WHERE WhatId In:oppIdsRelatedToEvents]; System.debug('Events that are related to Opportunities : ' + eventsList); This class is called from the Flow action element. I am not sure how to fix this error. Can the batch apex be the solution ? If so, how can I implement it from flow? Thanks Ramya