Say, I have a list of 1000 records to be inserted. How to capture those records that failed to get inserted? I realize that I can use DMLException to get the error. But how to get a list of failed insertions. Here's a situation I created to demonstrate my requirement.

Account[] accts = new List<Account>();
for(Integer i=0;i<1000;i++) {
Account a = new Account(Name='Acme' + i, BillingCity='San Francisco');
Account accountToUpdate;
   insert accts;        
catch(DmlException e) 
 System.debug('An unexpected error has occurred: ' + e.getMessage());

Say record Acme50 and Acme62 didn't get inserted. How to get a list of failed records?

  • 1
    Do you have to do this through code? i.e. is this for test coverage? Or would you be better to use the Data loader? – Nick Cook Jul 7 '14 at 5:39
  • Its not a requirement. Just curious about how to achieve this through apex. – MnZ Jul 7 '14 at 5:47

You need to use Database.insert() method and get results by using Database.SaveResult.

Also, have a look at the DML parameter optAllOrNone documented here. if you want to roll back the operation in case 1 record fails.

Example code:

List <Contact> contacts = new List <Contact> ();

Contact contact1 = new Contact();
contact1.FirstName = 'TestFirstname';
contact1.LastName = 'TestSurname';

Contact contact2 = new Contact();
contact2.FirstName = 'TestFirstname';

// Assuming contact2 will fail not having last name populated
List <Database.SaveResult> saveResults = Database.insert(contacts, false);

// Go through each result
for (Database.SaveResult saveResult : saveResults)
    if (saveResult.isSuccess() == true)
        // Successfully inserted contact
        // do something 
        // Failed
        for(Database.Error error : saveResult.getErrors())
            System.debug('Something went wrong with the record ID ' + saveResult.getId() + ' : ' + error.getStatusCode() + ' - ' + error.getMessage());
|improve this answer|||||
  • Sorry for the late acceptance. A cue from a fellow stackexchange user. Thanks #rao – MnZ Oct 22 '14 at 18:29

I tried with same code in case of failure but saveResult.getId() is null. we need the ids of the failure records.


Salesforce says if it not success then saveResult.getId() will be blank.

Any idea how to capture the failure records ID?

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.