Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

What is database insert (list, false) in apex?

Asked by Abigail Abraham Sep 22, 2022 6.0K views 2 answers
Share

About this question

 I am creating a List of Accounts, using Database.Insert (list,false) if I did give a name for a record in the list, it would skip that particular and insert the remaining records, is there any chance to get the details of the skipped record.

Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Jun 5, 2024

In Apex, the Database.insert method allows you to insert records into the database, with the option to specify whether to perform a partial or full insert operation.

Database.insert(recordsToInsert, allOrNone);

Parameters:

  1. recordsToInsert: The list of records you want to insert.
  2. allOrNone: A boolean flag that determines the transaction behavior.

Behavior of allOrNone:

True: If set to true, the entire operation is rolled back if any record fails to insert. This is similar to using the insert DML statement.

False: If set to false, the method attempts to insert all records. If some records fail, the others will still be inserted. You can then handle the failed records separately.

Example:

  // Create a list of accountsList accountsToInsert = new List();accountsToInsert.add(new Account(Name='Account 1'));accountsToInsert.add(new Account(Name='Account 2'));// Attempt to insert the accounts with partial success allowedDatabase.SaveResult[] results = Database.insert(accountsToInsert, false);// Process the resultsfor (Database.SaveResult sr : results) {    if (sr.isSuccess()) {        System.debug('Successfully inserted account with ID: ' + sr.getId());    } else {        for (Database.Error err : sr.getErrors()) {            System.debug('Failed to insert account: ' + err.getMessage());        }    }}

In this example:

  • We create a list of Account records to insert.
  • We call Database.insert with the list and false for the allOrNone parameter, meaning partial inserts are allowed.

  • We then process the SaveResult array to handle successes and errors individually.

This method is useful when you want to ensure that valid records are inserted even if some records in the batch fail due to validation rules, required fields, or other issues.

Was this helpful?

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.