Earn a Salesforce AI Certification by IIT + 12-Week Internship Secure Your Spot Today!

Earn a Salesforce AI Certification by IIT + 12-Week Internship Secure Your Spot Today!
How To Avoid DML from For Loop in Salesforce?

How To Avoid DML from For Loop in Salesforce?

In the world of Salesforce, efficiency, and optimization are not just buzzwords—they are essential practices that can significantly impact the performance and scalability of your applications. One common pitfall that developers encounter is the use of DML (Data Manipulation Language) operations within loops. This practice can lead to a host of issues, including hitting governor limits, which can bring your application to a grinding halt. 

In this blog, we’ll explore why it’s crucial to 

  • avoid DML operations inside loops in Salesforce and 
  • how to structure your Salesforce flows for optimal performance.

Understanding the Issue

DML operations, such as insert, update, delete, and upsert, are used to modify database records. When these operations are placed inside a loop, each iteration triggers a separate transaction, which can quickly consume the governor limits imposed by Salesforce’s multitenant architecture. Such limitations can lead to reduced code performance and may cause unforeseen errors or system failures.

Online Bootcamps India

What is the DML limit in Salesforce flow?

In Salesforce, managing DML operations within flows is critical to avoid hitting governor limits and ensure optimal performance. The platform enforces a limit of 150 DML statements per transaction, which means each insert, update, delete, or upsert counts towards this cap. Furthermore, there is a maximum limit of 10,000 records that DML statements are able to handle within a single transaction. To stay within these boundaries, it’s best practice to aggregate records into collections and perform DML operations outside loops. 

Also Read – How To Bulkify Salesforce Flows

Strategies to Avoid DML Operations Inside Loops

  1. Bulkify Your Code: The key to avoiding DML operations inside loops is to bulkify your code. This means aggregating your data into collections and performing DML operations on these collections outside the loop.
  2. Leverage Collections: Use lists, sets, or maps to collect records as you iterate through loops. Once the loop is complete, you can then perform a single DML operation on the entire collection.
  3. Utilize Salesforce Best Practices: Salesforce provides guidelines for writing efficient code, which includes using maps to hold data and performing DML operations on map values.
  4. Implement Error Handling: It’s essential to have a solid error management strategy when conducting DML operations on large datasets to identify and manage any exceptions that arise.

Example Solution

Here’s a simplified example of how to restructure code to avoid DML operations within a loop:

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;

    }

}

Conclusion

Avoiding DML operations within 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 remain within Salesforce’s governor limits. Remember, efficient code leads to efficient applications, which in turn leads to satisfied users and a robust Salesforce environment.

Ready to take your Salesforce skills to the next level? Join our saasguru community on Slack for a collaborative learning experience. Engage with experts, share insights, and stay ahead of the curve in the Salesforce ecosystem. 

Plus, don’t miss out on our online Salesforce bootcamps, where hands-on training and real-world projects prepare you for success. Dive in now and transform your career with saasguru!

Table of Contents

Subscribe & Get Closer to Your Salesforce Dream Career!

Get tips from accomplished Salesforce professionals delivered directly to your inbox.

Looking for Career Upgrade?

Book a free counselling session with our Course Advisor.

By providing your contact details, you agree to our Terms of use & Privacy Policy

Unlock Your AI -Powered Assistant

Gain Exclusive Access to Your Salesforce Copilot

Related Articles

Mass Assign User Permission Set in Salesforce

Learn how to efficiently mass assign user permission sets in Salesforce using tools like Data Loader. Save time and ensure accuracy. Read now!

How to Clone a FlexCard in Salesforce

Learn how to clone a FlexCard in Salesforce with this step-by-step guide. Simplify customization and boost efficiency effortlessly!

Salesforce Introduces Agentforce 2.0: Redefining How Work Gets Done

Salesforce introduces Agentforce 2.0, the AI platform transforming digital labor with autonomous agents and seamless workflows. Read now!