I am migrating records to Salesforce.com, and therefore need to check total record counts frequently. Some objects have over 500,000 records.
The simple 'Count' functions max out at 50,000 records so I therefore created a quick generic Batchable class to help, which really works fine, and takes about 6 minutes to count the 500k records.
The question I have is whether there is a faster way of doing this? Salesforce knows how many batches would be required before execution, so in theory it should be possible to count the number of batches along with the count of records in the final batch for the total.
global class CountingExample implements Database.Batchable<sObject>, Database.Stateful {
private Integer count = -1;
private string objectName = '';
global CountingExample(String newObjectName){
objectName = newObjectName;
count = 0;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
String query = '';
query = 'SELECT ID FROM ' + objectName;
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope) {
count += scope.size();
}
global void finish(Database.BatchableContext BC) {
try {
// Record total count here
}
catch(DmlException e)
{
System.debug('An unexpected error has occurred: ' + e.getMessage());
}
}
}


