I have a batch apex in which I am trying to insert 1000 records at a time. I am using Database.insert() to insert the records.For this is there any way to get the count of records that has been inserted successfully and the count of records that has failed during insert?


3 Answers 3


For that you'll need to use Database.SaveResult and iterate through the results to check whether it's a success or a fail:

Database.SaveResult[] saveResult = Database.insert(accounts, false);
Integer counter = 0;

for (Database.SaveResult sr : saveResult) 
    if (sr.isSuccess()) 

system.debug(counter); // Total number of successfully inserted accounts

Can't give you code but you can proceed with following hints:-

  • Implement Database.stateful with your batchable inteface
  • Declare two/one instance variable which will store failed and successful insert records information
  • Leverage Database.insert result as:

    Database.SaveResult[] srList = Database.insert(accts, false);

    // Iterate through each returned result
    for (Database.SaveResult sr : srList) {
        if (sr.isSuccess()) {
            // Operation was successful, so get the ID of the record that was processed
            // fill list with successfult IDs + sr.getId()); // new Ids
        else {
            // Operation failed, so get all errors                
            for(Database.Error err : sr.getErrors()) {
                // get error fields and other stuff from Error class
  • After it, in finish() method you can collect and process information for failed and successful records.


You have to implement Database.Stateful in your batch class and then you can have instance variables that don't lose state between batches.

global class implements Database.Batchable<sobject>, Database.stateful{

  public String query = 'Select id from Opportunity' ; 
  public Integer totalAmtOfRecords = 0; 

  global Database.QueryLocator start(Database.BatchableContext BC) {
     return Database.getQueryLocator(query);

   global void execute(Database.BatchableContext BC, List<sobject> scope) {  
      totalAmtOfRecords += scope.size();
      //your logic ...

     global void finish(Database.BatchableContext BC) {
        // Print Total amount of records processed in Batch Job
        system.debug('Total amount of records processed :' + totalAmtOfRecords);  


For more details check : How To Get Total Amount Of Records Processed In Batch Job In 10 Minutes And Still Look Your Best

  • I don't think this really matches up with the question. The OP wants to insert records (so a query doesn't make sense as your constructor) and you'll want to loop through the partial save results to determine which succeeded and which failed.
    – Adrian Larson
    Commented Dec 21, 2016 at 18:08

You must log in to answer this question.

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