According to the documentation, in a batch a Database.QueryLocator can retrieve up to 50 million records.

A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed.

I then cycle through them in batches, default size 200, maximum size 2000. When I run a batch, Salesforce knows how many batches there are, so it must know how many records are in the QueryLocator. But can I find out? The only methods I can see on the QueryLocator are these two:

getQuery() Returns the query used to instantiate the Database.QueryLocator object. This is useful when testing the start method.

iterator() Returns a new instance of a query locator iterator.

I want to know what the total size of the record set is, before I go through all the batches.

  • Really looking forward to some insights on this! Salesforce use their super powers to recurse to the end of the data set with QueryLocators and Custom Iterators, which always surprised me as I figured that to be a one way function! Wonder if they are cloning the cursor under the covers and consuming that to accumulate the count. Commented Dec 21, 2014 at 16:13
  • 2
    According to andy fawcett, in batch the query start stores away the entire recordset which is then consumed as if from a cache by the execute method. So somewhere the platform has already completed the query.
    – Dominic
    Commented Dec 21, 2014 at 21:53

2 Answers 2


Try running a SELECT COUNT() FROM ... query in your start method before calling QueryLocator.


As per the documentation, we do not have any existing functions to get the size.


You can use the following code to get the total size of returned values:-

global class YourBatchClass implements Database.Batchable<sObject>, Database.Stateful{
global Integer countVariable=0;

global Database.QueryLocator start( Database.BatchableContext BC ) {
    String queryStr =   'select id,name from Contact';
    Database.QueryLocator queryResult= Database.getQueryLocator( queryStr );       
    // Get an iterator
    Database.QueryLocatorIterator i =  queryResult.iterator();
    // Iterate over the records
    while (i.hasNext())
    system.debug('Total returned Records: '+countVariable);
    return queryResult;

You must log in to answer this question.

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