top of page

Difference between Insert and Database.Insert in Salesforce

Insert:

  • Partial insert is not supported.

  • Roll back is not supported.

  • If we use the DML statement (Insert) in bulk operation, then if error occurs the execution will stop. In that case Apex code throws an error and none of the record will insert to the database.


Database.Insert:

  • Partial insert is supported.

  • Roll back is supported.

  • Includes the optional allorNone parameters that defaults true.

  • If we use DML database methods (Database.Insert) in bulk operation, then if error occurs the remaining records will be inserted means partial DML operation will be done. The only record throwing an error will not be inserted.

Example with code: We know Account's Name field is required.


StandaloneDML()

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


lstAcc.add(new Account(Name = 'Test Acc 01'));

lstAcc.add(new Account(Name = 'Test Acc 02'));


insert lstAcc ;


check your org you can see 2 records created


databaseMethodDML()

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


lstAcc.add(new Account(Name = 'Test Account 001'));

lstAcc.add(new Account(Name = 'Test Account 002'));

lstAcc.add(new Account(Name = 'Test Account 003'));

lstAcc.add(new Account());

lstAcc.add(new Account());


Database.insert(lstAcc);


Try this code you will get error.


Line: 9, Column: 1 System.DmlException: Insert failed. First exception on row 3; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Name]: [Name]


databaseMethodPartialCommit()

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


lstAccount.add(new Account(Name = 'Test Account 001'));

lstAccount.add(new Account(Name = 'Test Account 002'));

lstAccount.add(new Account(Name = 'Test Account 003'));

lstAccount.add(new Account());

lstAccount.add(new Account());


Database.insert(lstAccount, false);


check your org you can see 3 records created Test Account 001,Test Account 002 and Test Account 003



Recent Posts

See All
Batch Apex in Salesforce

Batch class in salesforce : When we want to deal with large number of records we go for batch apex. The code inside batch class runs...

 
 
 

Commentaires


Subscribe to Path2sfdc newsletter

Thanks for submitting!

  • Twitter
  • trailhead
  • Linkedin

© 2024 by Path2sfdc

bottom of page