1

I cannot understand why I am receiving the following error:

Too many query rows: 50001

The first two queries work perfectly when using COUNT( id), but the last two Contacts_Reached_TR_120_Query and Accounts_Reached_TR_120_Query receive this error. Is there something wrong with using COUNT_DISTINCT. I also would like to note that the Aggregate Result is only returning six rows.

String Contacts_Created_TR_120_Query = 'SELECT CreatedByID SDR_ID, COUNT( id ) result FROM Contact Where CreatedDate = LAST_N_DAYS:120 AND CreatedById in :ListOfIDs GROUP BY CreatedById';
DynamicBatchApexAR batch1_TR120      =   new DynamicBatchApexAR('SDR_ID', 'result', 'Contacts_Created_TR_120__c', Contacts_Created_TR_120_Query, SDR_IDs);

String Accounts_Created_TR_120_Query = 'SELECT CreatedByID SDR_ID, COUNT( id ) result FROM Account Where CreatedDate = LAST_N_DAYS:120 AND CreatedById in :ListOfIDs GROUP BY CreatedById';
DynamicBatchApexAR batch2_TR120      =   new DynamicBatchApexAR('SDR_ID', 'result', 'Accounts_Created_TR_120__c', Accounts_Created_TR_120_Query, SDR_IDs);

String Contacts_Reached_TR_120_Query = 'SELECT Ownerid SDR_ID, COUNT_DISTINCT( whoid ) result FROM Task Where ActivityDate = LAST_N_DAYS:120 AND OwnerId in :ListOfIDs GROUP BY Ownerid';
DynamicBatchApexAR batch3_TR120      =   new DynamicBatchApexAR('SDR_ID', 'result', 'Contacts_Reached_TR_120__c', Contacts_Reached_TR_120_Query, SDR_IDs);

String Accounts_Reached_TR_120_Query = 'SELECT Ownerid SDR_ID, COUNT_DISTINCT( accountid ) result FROM Task Where ActivityDate = LAST_N_DAYS:120 AND OwnerId in :ListOfIDs GROUP BY Ownerid';
DynamicBatchApexAR batch4_TR120      =   new DynamicBatchApexAR('SDR_ID', 'result', 'Accounts_Reached_TR_120__c', Accounts_Reached_TR_120_Query, SDR_IDs);
1
  • What is the API version of this class?
    – javanoob
    Commented Oct 11, 2019 at 2:05

1 Answer 1

1

Take a look at this question from sfdcfox:

The number of rows aggregated count against the 50,000 record limit. The "Rows" value you're seeing are the number of aggregate rows that were returned; this has a limit of 2,000 rows per query; if you exceed that, you'll get a different sort of error. Without knowing more, it's hard to tell what you'll need to do, but it may involve writing a batch class, using the @ReadOnly annotation, or filtering the data differently. This is mentioned in the documentation:

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. (Emphasis added)

1
  • I am writing a batch class and still getting this error - Can we just not batch using COUNT_DISTINCT? Commented Oct 10, 2019 at 18:25

Not the answer you're looking for? Browse other questions tagged .