I have a batch job that reads records from a table and does some processing. During the execute method, these records are deleted.

This job can, under certain circumstances, be running more than once. I am worried about an instance in which the records that Job #2 is trying to process have been deleted by Job #1.

The question is:

How does the Database.QueryLocator works? Will it attempt to retrieve (or somehow earmark) all the records during the start method or will a quick query be run before each execute method?

If it's the latter, I feel ok about my job. If it's the former, what do you suggest to avoid my scenario?

  • Just to clarify, you're speaking of a single batch job that queries less than 200 records? Otherwise, like triggers, any batch job runs in separate "chunks" of 200 records at a time. Those records can be locked if in use by another process, at which point contention & concurrency becomes an issue.
    – crmprogdev
    Mar 25, 2016 at 20:53
  • So, not quite. I am talking about hundreds of thousands of records. concurrency is not a problem in my case (it doesn't bother me that I might be processing the record twice) but contention is what I am concerned about. The question is, will the queryMore potentially get records that have already been deleted? Mar 25, 2016 at 20:59
  • 2
    Here's some additional info about the QueryLocator behavior that might inform the answer a bit: salesforce.stackexchange.com/a/96871/660
    – Mark Pond
    Mar 25, 2016 at 21:08
  • @MarkPond Make that an answer so I can accept it.... That was the answer I needed.... though not the one I hoped for. Mar 25, 2016 at 21:10
  • 1
    @Mo, I agree, based on Mark's answer. I can code to account for that, so I think I'll be fine in the end. Mar 25, 2016 at 21:11


Browse other questions tagged .