I am inserting multiple records using Apex DML; e.g.

List<Account> accounts = new List<Account>();

// Populate the accounts list

insert accounts;

If there is any kind of error inserting any of the records, the insert fails for the entire batch. Is there a way to make the insert not fail if one record fails?


Use a DML database method with a value of false for the optional opt_allOrNone parameter - i.e.

Database.SaveResult[] result = Database.Insert(accounts, false);

From the docs,

Use DML database methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the operation. When using this form, you can write code that never throws DML exception errors. Instead, your code can use the appropriate results array to judge success or failure. Note that DML database methods also include a syntax that supports thrown exceptions, similar to DML statements.

| improve this answer | |
  • 2
    Also, using the optional allOrNone parameter will allow the remainder of the operation to succeed. Database.insert(accounts, false); see salesforce.com/us/developer/docs/apexcode/Content/… – DerekLansing Sep 27 '12 at 16:24
  • @DerekLansing good catch, thanks! Edited my answer – metadaddy Sep 27 '12 at 16:31
  • However if a trigger throws an unhandled exception it will mark all objects in that trigger context as failed. – ca_peterson Sep 28 '12 at 1:30
  • @ca_peterson Moral of the story: catch your exceptions :-) – metadaddy Oct 16 '12 at 1:05
  • @metadaddy Gr8 post! I have a question. How do I capture those records that failed to get inserted? – MnZ Aug 6 '14 at 11:01

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.