Using Aggregate SOQL queries/results in Batch Apex

In previous post, we had created a schedulable batch apex that implements Database.Batchable<sObject> in Salesforce, but if you want to use SOQL having aggregate functions like SUM(), MAX(), COUNT() on results grouped by “GROUP BY” clause in start execution, changing to interface Database.Batchable<AggregateResult> isn’t a workable way, because it fails with the below compile error :

Class must implement the global interface method: Iterable<AggregateResult> start(Database.BatchableContext) from Database.Batchable<AggregateResult>

The following sample code will explain this.

To fix this, using Apex classes that implement Iterator<AggregateResult> and Iterable<AggregateResult> seems the only way for now.

Here is the outline what we should do.
1. Create an Apex class implements Iterator<AggregateResult>.
2. Create an Apex class implements Iterable<AggregateResult>.
3. Implementing to Database.Batchable<AggregateResult>, and Using Iterable at start execution in Batch Apex.

Let’s get started.

Iterator Apex class

Create an Apex class named “AggregateResultIterator” with the following source code :

Iterable Apex class

Create an Apex class named “AggregateResultIterable” with the following source code :

Batch Apex

Then implement Batch Apex from Database.Batchable<AggregateResult>, and use Iterable<AggregateResult>, AggregateResultIterable instead of Database.QueryLocator at start execution, as the following source code :

Operation check

Run SampleAggregateBatch and check debug log.

It seems working fine! : )

Enjoy it!

Related Post

Writing a Schedulable Batch Apex in Salesforce To use batch Apex, you have to create an Apex class that implements interface Database.Batchable in Salesforce, like the following sample code: Execute batch Then you can use Database.executebatch method to execute it. https://gist.g...
Write a Heroku Scheduler batch for MangoDB+Salesfo... In previous post,I had shared how to 《Access Salesforce data via APIs(JSForce) from Outside Service》. In this post I will share about how to write a Heroku Scheduler batch for synchronizing MangoDB data to Salesforce with Node.js, like the below outline picture. ※I have no doubt that there hav...
Salesforce RemoteAction and webService In Salesforce,we can make asynchronous requests from Visualforce Page,via RemoteAction or webService. I will share you the usage of RemoteAction and webService In this post. RemoteAction Using RemoteAction(JavaScript Remoting) allows us to call methods in Apex controllers and get a callback wit...
Catching and customizing Apexpages Messages in Ape... As we know, apex:pageMessages tag can be used to display all messages that were generated for all components on the current page, presented using the Salesforce styling, as the following source code we use: Controller Class(CommunitiesSelfRegController)