How to Avoid DML Operations from For Loops in Salesforce

How to Avoid DML Operations from For Loops in Salesforce

On May 24, 2025, Posted by , In Apex, With Comments Off on How to Avoid DML Operations from For Loops in Salesforce

Table Of Contents

In Salesforce development, optimizing code for performance and scalability is paramount. One common mistake that developers make is performing DML (Data Manipulation Language) operations inside loops. While this may seem like an easy solution, it can result in hitting Salesforce’s governor limits, causing system errors or slow performance. In this blog post, we will discuss why you should avoid placing DML operations inside loops and how to structure your Salesforce flows for better efficiency.

CRS Info Solutions provides a real-time Salesforce Course tailored for beginners, aimed at equipping participants with hands-on expertise and essential industry skills in Salesforce. Sign up now for a free demo session!

Understanding the Issue

Salesforce’s governor limits are designed to ensure fair resource usage across the multitenant environment. One of these limits pertains to the number of DML statements you can execute in a single transaction. If DML operations are placed inside a loop, Salesforce will execute them multiple times, increasing the risk of hitting governor limits and degrading performance. This could lead to errors like “Too many DML statements” or “Query rows returned greater than limit,” causing your application to fail.

When using operations like insert, update, delete, or upsert inside loops, each iteration executes a separate transaction. For example, if you are processing 100 records, and you perform DML operations inside a loop, you will end up executing 100 DML statements, quickly exceeding the 150 DML limit Salesforce imposes per transaction. Moreover, Salesforce only allows 10,000 records to be processed per transaction, and violating these limits will cause your app to malfunction.

See also: Are Salesforce Certification Exam Dumps Really Worth the Risk?

DML Limits in Salesforce

In Salesforce, the platform enforces strict governor limits on DML operations. The most important limits to be aware of are:

  • 150 DML Statements per transaction: Each DML operation (insert, update, delete, upsert) counts towards this limit. Exceeding this limit can trigger errors.
  • 10,000 Records: A single DML statement can handle up to 10,000 records. Processing more records requires breaking them into smaller batches.

To avoid hitting these limits, you should aggregate records into collections and perform DML operations outside of loops.

See also: Top LWC Interview Questions 2025

Strategies to Avoid DML Operations Inside Loops

Here are key strategies to avoid DML operations inside loops and optimize your Salesforce code:

  1. Bulkify Your Code: The key to efficient Salesforce development is bulkification. Bulkifying means processing records in batches rather than individually, which prevents hitting governor limits. You can achieve this by collecting data in lists or sets and performing DML operations outside of loops.
  2. Leverage Collections: Use lists, sets, or maps to collect records during the loop. Once the loop completes, you can then perform a single DML operation on the entire collection. This reduces the number of DML statements executed and optimizes performance.
  3. Salesforce Best Practices: Salesforce provides best practices for writing efficient code, including using maps to hold data and performing DML operations on map values. This ensures that you work with large data sets efficiently.
  4. Error Handling: When performing DML operations on large datasets, ensure you have proper error handling in place. This helps you manage exceptions and maintain smooth operations even when dealing with massive amounts of data.

Example Solution

Here’s a simplified code example that demonstrates how to restructure code to avoid DML operations within loops:

public class OpportunityTriggerHandler {

    public static void processOpportunities(List<Opportunity> oppList) {

        List<CustomObject1> object1List = new List<CustomObject1>();

        List<CustomObject2> object2List = new List<CustomObject2>();

        // First, collect the data for CustomObject1
        for (Opportunity opp : oppList) {
            CustomObject1 obj1 = new CustomObject1();
            // Set fields on obj1 based on Opportunity
            object1List.add(obj1);
        }

        // Perform a single DML operation for CustomObject1
        insert object1List;

        // Now, collect the data for CustomObject2 using the inserted CustomObject1 records
        for (CustomObject1 obj1 : object1List) {
            CustomObject2 obj2 = new CustomObject2();
            // Set fields on obj2, including the relationship to obj1
            object2List.add(obj2);
        }

        // Perform a single DML operation for CustomObject2
        insert object2List;
    }

}

In this example, instead of inserting CustomObject1 and CustomObject2 within their respective loops, we collect all records in lists (object1List and object2List). Once the loop finishes, we perform the insert operation on each list in bulk.

Explanation:

  • Bulkification: Instead of executing DML (insert) inside the loop for each record, the code collects the records in lists (object1List and object2List).
  • DML outside loops: After all data is collected, the insert operation is performed once for each list (object1List and object2List), reducing the number of DML operations.
  • Performance Improvement: This ensures that DML operations are not called repeatedly within a loop, preventing Salesforce’s governor limits from being exceeded and improving overall performance.

See also: Salesforce Einstein Interview Questions

Additional Example: Avoiding DML in For-Loop with Updates

Let’s consider another example where we need to update records in a loop. Instead of executing DML inside the loop, we gather the records in a list and update them in bulk:

public class AccountHandler {

    public static void updateAccounts(List<Account> accountsToUpdate) {
        List<Account> updateList = new List<Account>();
        
        for (Account acc : accountsToUpdate) {
            acc.Status__c = 'Updated';  // Update the status field
            updateList.add(acc);  // Add to the update list
        }
        
        // Perform a single DML update outside the loop
        update updateList;
    }

}

In this case, all account records are updated in bulk after the loop finishes, reducing the number of DML statements.

Explanation:

  • Bulkified Update: In this example, we need to update the Status__c field of multiple account records. Instead of performing the update operation inside the loop, we first collect all the Account records into the updateList.
  • Single DML Operation: After the loop finishes, the update operation is performed on the entire updateList in one go, which minimizes the number of DML statements and helps stay within Salesforce’s governor limits.
  • Efficiency: By executing the DML statement once, the code avoids hitting the governor limit for DML operations and performs the update efficiently.

See also: 10 Highest Paying Salesforce Jobs in 2025

Conclusion

Avoiding DML operations inside loops is a fundamental best practice in Salesforce development. By bulkifying your code and using collections effectively, you can ensure that your applications run smoothly and stay within Salesforce’s governor limits. The performance of your code is directly tied to how well you manage DML operations. Efficient code leads to efficient applications, which leads to a better user experience and a more robust Salesforce environment.

Learn Salesforce Course at CRS Info Solutions

For those who want to dive into the world of Salesforce, CRS Info Solutions offers a comprehensive Salesforce course designed to guide beginners through every step of the learning process. Their real-time Salesforce training is tailored to provide practical skills, hands-on experience, and in-depth understanding of Salesforce concepts. As part of this Salesforce Course, you’ll have access to daily notes, video recordings, interview preparation, and real-world scenarios to help you succeed.

By choosing to learn Salesforce with CRS Info Solutions, you gain the advantage of expert trainers who guide you through the entire course, ensuring you’re well-prepared for Salesforce certification. This training not only equips you with essential skills but also helps you build confidence for your job search. If you want to excel in Salesforce and advance your career, enrolling in a Salesforce course at CRS Info Solutions is the perfect starting point.

Comments are closed.