2

In Start Method I use Aggregated Query (queries use GROUP By ),then how to check In Execute Method the Aggregate Query how much record Fetch Limit & Number of records we can get using Aggregate Query

here I'm trying like

    global class AggregateQueryBatch implements Database.Batchable<AggregateResult> {
    
    global Iterable<AggregateResult> start(Database.BatchableContext bc){
        String query = 'SELECT COUNT(Id), Account__c FROM account_allowances__c GROUP BY Account__c';
        return new AggregateResultIterable(query);
    }    
    global void execute(Database.BatchableContext bc, List<sObject> scope){ 
        for(sObject sObj : scope) {
          AggregateResult ar = (AggregateResult)sObj;
          System.debug('>>>> COUNT : ' + ar.get('cnt'));
        }
    }
    global void finish(Database.BatchableContext bc){
    }
}

and get error like "Invalid type: AggregateResultIterable" please give me the best suggestion to find the limit and number of record fetch by using of Aggregate Query. Here "account_allowances__c" have more then 50,000 record Thanks

1
  • Just a general note that in programming, you can't just type whatever you want. You need to use classes/methods/variables that the language provides to you (things like List<AggregateResult>, Opportunity, JSON.deserialize()) or define them yourself if they don't exist. AggregateResultIterable isn't provided by Apex, and you haven't made an Apex class for that, so you, unsurprisingly, get an error.
    – Derek F
    Commented Aug 23, 2022 at 14:32

1 Answer 1

1

You'd do an inline query:

public Iterable<AggregateResult> start(Database.BatchableContext context){
    return [SELECT COUNT(Id), Account__c FROM account_allowances__c GROUP BY Account__c];
}    

Note that you'll be limited to 2,000 accounts in this case, otherwise you'll get an exception, because AggregateResult queries do not generate database cursors.

It would be better to start from accounts and work backwards:

public Database.QueryLocator start(Database.BatchableContext context) {
    return Database.getQueryLocator([
      SELECT Id FROM Account WHERE Id IN (SELECT Account__c FROM Account_Allowances__c)
    ]);
}

This query will work for up to 50,000,000 records. In your execute method, you can then figure out how many account allowances there are for the selected accounts:

public void execute(Database.BatchableContext context, Account[] scope) {
  Account_Allowances__c[] allowances = [
    SELECT Account__c 
    FROM Account_Allowances__c 
    WHERE Account__c = :scope
  ];
  // rest of code
}
2
  • Thanks for your response My question is When I use Aggregate query in batch class, How many record we can Fetch?
    – sunny roxx
    Commented Aug 24, 2022 at 3:20
  • @sunnyroxx 2,000 aggregate rows.
    – sfdcfox
    Commented Aug 24, 2022 at 11:25

You must log in to answer this question.

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