Bulkification
Not Started

Before learning about the other DML operation types, we know enough to pause and talk about a serious topic: Bulkification.

Consider this our version of the birds and bees talk. :)

Salesforce is multi-tenant, you know this. Resources are shared and governor limits are put into place to protect those shared resources. Now that you know about DML we'll talk about protection.

150 DML statements per transaction

You're issuing a DML statement each time you use the insert keyword. You can only issue 150 DML statements per transaction. So, don't do this:

for(Integer i = 0; i < 200; i++){ String accName = 'Account #' + String.valueOf(i); Account acc = new Account(Name=accName); insert acc; }

The DML happens inside the for loop, which means a DML statement is issued once per iteration. There are 200 iterations in this for loop, so by the time we hit the 151st iteration, our program will halt with the following limit exception: System.LimitException: Too many DML statements: 151.

Instead, bulkify your DML by inserting a list of account records and moving the DML outside of the for loop:

// TODO: Create 200 Account records List<Account> accRecords = new List<Account>(); for(Integer i = 0; i < 200; i++){ String accName = 'Account #' + String.valueOf(i); Account acc = new Account(Name=accName); accRecords.add(acc); } insert acc;



With this implementation, we issued only 1 DML statement and processed 200 account records. Not only does that keep us well under the governor limit, but it also makes our program more efficient because we interact with the database fewer times. This practice applies to all DML types, not just insert.

One more thing you can do to reduce DML statements while we're here is to combine DML statements of different sObject types into one. For example:

Account acc = new Account(Name = 'Apple Inc'); insert acc; Event__c customEventRecord = new Event__c(Name='Dev Conference'); insert customEventRecord;

This issues 2 DML statements. There's nothing inherently wrong with this. However, an argument could be made to combine these DML calls. We'll use a list of the generic type, sObjectto do that.

List<sObject> recordsToInsert = new List<sObject>(); Account acc = new Account(Name = 'Apple Inc'); recordsToInsert.add(acc); Event__c customEventRecord = new Event__c(Name='Dev Conference'); recordsToInsert.add(customEventRecord); insert recordsToInsert;

We just turned 2 DML statements into 1. Keep bulkification top of mind while you're writing Apex, especially when you're writing Triggers, DML, and SOQL.

Challenge

A list of Book records are passed into the method that's not bulkified. Refactor the method to bulkify the DML to use only 1 insert statement.