Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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
up vote 5 down vote accepted

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());
share|improve this answer
Sorry for the late acceptance. A cue from a fellow stackexchange user. Thanks #rao – MnZ Oct 22 '14 at 18:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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