Monday 21 August 2017

Insert vs Database.insert() in Salesforce

Insert

Insert is a DML statement which is same as Database.insert to insert the record in database. If we use insert DML statement in bulk operation if error occurs in this operation, then execution stop and rollback all the insertion from the database those has been inserted successfully. When error occurs then you can handle this error by try catch block.

Database.Insert

If we use DML database method (Database.insert) to insert/update record in bulk, then if error occurs the remaining records will be inserted/updated means partially operation will be done.

Just take an Example:

If you are inserting 4 records.
2 having all the required fields value and remaining 2 records missing required fields value.
if you use
Database.insert(list) will throw an exception and it will not insert any one of the records.

But
if you use Database.insert(list, false) It will insert 2 records successfully and rest 2 records (required fields missing) will not be inserted.
Database.insert(list, false) In this scenario you will not get any exception

Example with Code:

List<Account> lstAccount = new List<Account>();
lstAccount.add(new Account(Name = 'Test Account 1'));
lstAccount.add(new Account(Name = 'Test Account 2'));
lstAccount.add(new Account());
lstAccount.add(new Account());
Database.insert(lstAccount);
If you execute this code you will get error shown below:-

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

Now run below code:

List<Account> lstAccount = new List<Account>();
lstAccount.add(new Account(Name = 'Test Account 1'));
lstAccount.add(new Account(Name = 'Test Account 2'));
lstAccount.add(new Account());
lstAccount.add(new Account());
Database.insert(lstAccount,false);
If you execute this code you can see 2 records will be inserted in your org Test Account 1 and Test Account 2 and not throw any error.
If you use Database.insert(lstAccount,true) then you will find same error as above.

Difference between Database.insert(lstAccount.false) and Database.insert(lstAccount,true)

If you insert records using Database.insert(lstAccount,false) and any error comes in between record inserting like some records are getting insert due to required field blank then this statement does not throw error while insertion then insert the right record and do not insert error records.

If you insert records using Database.insert(lstAccount,true) then this statement behave as an insert DML statement. If error comes in between record inserting like some records are getting insert due to required field blank, then this statement throws error and does not insert any record i.e. rolled back whole process. 

6 comments:

If you have any doubts, please let me know.