Avoid DML from For Loop in Salesforce

Join us to learn about how to avoid DML from For Loop in Salesforce? To avoid DML (Data Manipulation Language) statements inside a for loop in Salesforce, you can use the bulk update technique. This technique involves creating a list of records that need to be updated and then updating them all at once outside the for loop.

Why DML should not be written inside for loop?

The well-known Salesforce governor limit concerns the number of DML operations in a single transaction. As per the docs, the limit is 150.

Here is one simple code that will give you the “Too Many DML Statements: 151” error.

for (Integer i = 0; i < 150; i++){    
   Account accountObject = new Account();  
   accountObject.Name = 'Test ' + i;    
   insert accountObject ;
}

How to fix Too Many DML Statements: 151

You should not use a DML statement inside for loops and leverage collections to store the data, and then when you do a DML operation on a collection, it only counts as one DML!

List<Account> accountList = new List<Account>();
for (Integer i = 0; i < 150; i++){    
   Account accountObject = new Account();  
   accountObject.Name = ‘Test ‘ + i;  
   accountList.add(accountObject);  
}
insert accountList;

In the example above, we first create an empty list called `accountList`. Then, we loop through all the accounts and update their names. Instead of updating each account inside the loop, we add them to the `accountList` list. After the loop, we update all the accounts in the `accountList` list in a single DML statement outside the loop.

This avoids the DML statement inside the for loop, which can cause performance issues and governor limit exceptions in Salesforce. By using the bulk update technique, you can improve the efficiency and performance of your code in Salesforce.

How to avoid DML from For Loop in Salesforce

There are few other solution which you can follow to fix the DML inside for loop issue.

  1. Bulkify your code: The first principle is writing code for multiple records simultaneously. We should write scalable code and avoid hitting the governor.
  2. Use Collection: You can use List and MAP in Salesforce to avoid SOQL and DML inside the for loop.
  3. Follow Salesforce Apex Best practice: Learn about Salesforce Apex best practices to avoid any governor limit in Salesforce.

Learn more about Different types of Exceptions in Salesforce.

What is the DML limit in Salesforce flow?

The total number of DML statements issued is 150 in flow, and the Total number of records processed due to DML statements is 10,000. Learn more here.

Summary

DML statements should not be used inside loops. Learn different way to Overcome Salesforce Governor Limits Using Platform Events.

Leave a Reply

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