Here's the scenario: I have 1 million + 'Usage Data' records, which are related to Contracts via a lookup field. I want to get a count of the number of Usage Data records on each Contract.

My understanding is that I can't use aggregate SOQL queries due to the # of records involved (a single contract can have over a hundred thousand usage data records).

I'm working on a batch apex class that goes through chunks of usage data records. My thought was to query the related contracts list for each chunk of UD records, and add the count from that chunk to the existing count stored on a field on the contract object.


for each chunk of UD records
    build a list of related contracts
    add count of UD records in chunk to related contracts (contract.UDcount = UDcount + chunkcount)

The problem: Since I will need to rerun this batch apex regularly to update the counts, I need to initialize the "UD count" field on the contract to 0 before running the batch class. I can't just include it in the "execute" method of the batch class, because then it will reset the field to 0 for each new chunk, when instead I want it to remain static in between chunks.

So my first question is: can I use the "start" method in the batch class to call an initialization method that sets all my contracts' "UD Count" field = 0? I want to do this so all the steps for this process are contained in the same scheduled class (as opposed to writing a class that I run separately to initialize that field to 0).

My second question is: am I going about this overall project the best way, or is there a simpler method?

Thanks for the help all!

1 Answer 1


Batches can call other batches in the finish method. Therefore, use two batches. The first resets all records to zero, and the second performs the tallying. You could make this one class by passing in a different parameter into the constructor. Also, if you could simply use a master-detail relationship, a simple roll up field would suffice.

  • Thank you for the response. Had to drop this project for other more pressing work, but I hope to expand on this question later as I don't completely understand your comment.
    – smohyee
    Commented Apr 15, 2014 at 21:52

You must log in to answer this question.

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