Apex, Best Practice, Development, Dreamforce

You can you use DML in a for loop!


Some people may have have seen ‘Apex Ten Commandments’ that myself and Codefriar did at Dreamforce a while back.

One slide we didn’t know if we should put in or not was to come right at the end saying “Thou shalt feel free to break these rules as wisdom merits”. But the issue with this slide was two fold. The majority of developers the ten commandments was aimed at should be following the rules. But for more advanced developers you do at times need to twist the rules and they don’t make sense. Adding the slide could mean that junior developers think of the commandments are only loose guidelines. In the end we left it out but the following year Codefriar kept it in… and in hindsight a better idea 🙂

Rule #2 was “Thou shalt not put DML in for loops“:

But there is one scenario when you can actually have a DML in a for loop and that is when you have your for loop return a collection rather than a specific record.

for (Account a : [SELECT Id, Name FROM Account
 WHERE Name LIKE 'Acme%']) {
 // Your code here
 update a;
}
for (List accts : [SELECT Id, Name FROM Account
 WHERE Name LIKE 'Acme%']) {
 // Your code here
 update accts;
}

The second is better because Salesforce will return 200 records at a time into your for loop. So your DML will only fire once for every 200 records. There is another fringe benefit! Salesforce will clear the heap stack on every iteration thus helping to clear out that heap stack so you don’t hit a heap size limit, which is always good 🙂

Load More Related Articles
  • The Salesforce Learning Week!

    What a year! It’s around this time of year when I would be heading to Dreamforce (Salesforce’s biggest event of the ...
  • The Salesforce Capability Map

    The Salesforce platforms are huge and sometimes it’s hard to keep up with all the changes. These Salesforce capability maps are ...
  • New Salesforce News Podcast!

    So Anup and I have decided to create a new Salesforce podcast called the ‘Salesforce Posse Podcast’. We’ve just launched our ...
Load More By Francis Pindar
Load More In Apex

One Comment


  1. Jaime

    April 16, 2021 at 2:21 pm

    Hi! thanks for the tips
    I understand that the right logic would be like:

    for (List accts : [SELECT Id, Name FROM Account WHERE Name LIKE 'Acme%']) {
    for (Account acc : accts){
    acc.Phone = '123';
    }
    update accts;
    }

    Instead of:

    for (List accts : [SELECT Id, Name FROM Account WHERE Name LIKE 'Acme%']) {
    for (Account acc : accts){
    acc.Phone = '123';
    update accts;
    }
    }

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Check Also

The Salesforce Learning Week!

What a year! It’s around this time of ...

My Latest YouTube Video