1.5 Use Database Object to do DML operations

The concept

In our last post we have mentioned that DML statements only executes in one transaction. So what if we want some of the data to be persisted if we can, regardless of others may fail? Database operations will serve us for that purpose.

Remember the validation rule we have created in our last post? We still need it.

Below is our code for today:

Merchandise__c mer1 = new Merchandise__c();
mer1.name = 'Books';
mer1.Original_Price__c = 20;

Merchandise__c mer2 = new Merchandise__c();
mer2.name = 'Bike';
mer2.Original_Price__c = 300;

List<Merchandise__c> merList = new List<Merchandise__c>();
Database.insert(merList, false);

A bit explanation

Please note there is always only one line different from last post’s code: Line 12. And the result is different.

Database methods have two parameters, the first one is the list to be operated on, and the second one is whether it is all or none mode. If we choose false, it can be partially succeed mode. That’s why when we executed the above code, it successfully inserted one row into database.


Create a scenario where you need to update a list of records, and it partially succeed. Try to write the code.

Next Post

1.6 Initial understanding of governor limit and bulkification

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *