Added as many conditions as i could. Don't want to put a LIMIT as there are less than 76k Accounts of this particular record type.

Is there any other way to overcome the System.exception: Too many query rows ?

    Set<Id> setAttachmentParentId = new Set<Id>();
    for(Attachment a : [select ParentId from Attachment where parent.type = 'Account' AND ContentType ='application/pdf']){
    List<Account> listOfRecords= [SELECT ID 
                          FROM Account 
                          WHERE ID NOT IN : setAttachmentParentId AND External_ID__c NOT IN ('XXXXX','XXXXXX','duplic','noid') AND RecordTypeID = 'rttyyuyu' AND Status__c ='Active' AND CreatedByID != '005440AE' AND OwnerID!='00544000'];
    system.debug('The id is >>>> ' + listOfRecords.size());

1 Answer 1


Query rows are cumulative per transaction. The latter query might be less than 50k, but the total sum is not. If you just need the parentIds, try:

Set<Id> setAttachmentParentId = new Map<Id, AggregateResult>(
        select ParentId Id from Attachment where parent.type = 'Account' AND ContentType ='application/pdf' GROUP BY ParentId

This will work if there are less than 2,000 account records to be selected, as you no longer need to get all the attachments (it will count as one row per ParentId). Otherwise, you'll need to get creative, such as aggregate result queries in batches of 2000, or using a Queueable/Batchable class to get the information you need.

You must log in to answer this question.

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