The DML-in-a-Loop Problem
By the end of this lesson, you'll be able to:
- Identify DML running inside a loop as an anti-pattern
- Explain the specific limit it threatens (150 DML statements, not 100 SOQL)
- Recognize the twin nature of this problem alongside SOQL-in-a-loop
Prerequisites: "The SOQL-in-a-Loop Problem"
The anti-pattern, applied to DML
// DON'T DO THIS
for (Account acc : accountsToUpdate) {
acc.Industry = 'Technology';
update acc; // a separate DML statement on every single iteration!
}
This is Module 7's original bulkification example, revisited here with its specific governor limit named directly: 200 accounts means 200 separate update statements in one transaction, exceeding the 150-DML-statement limit.
Not just insert/update — delete counts too
// Also DON'T DO THIS
for (Opportunity opp : staleOpportunities) {
delete opp; // still one DML statement per iteration
}
Every DML statement — insert, update, delete, upsert, merge (Module 19) — counts toward the same 150-statement limit. The problem isn't specific to update; it's specific to any DML statement running once per loop iteration instead of once total.
Twin problems, same root cause
SOQL-in-a-loop and DML-in-a-loop are really the same mistake, threatening two different limits: doing a database operation (read or write) inside a loop instead of once, outside the loop. Recognizing them as one underlying pattern — not two unrelated rules to memorize — is what makes the fix (the next lesson) apply cleanly to both.
Exercise
As a comment, explain why running delete inside a loop threatens the same limit as running update inside a loop.
Show hint
Think about what all DML statement types have in common.
The DML-in-a-Loop Problem Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
DML inside a loop is the direct sibling of the SOQL-in-a-loop problem — the same shape, threatening a different limit (150 DML statements instead of 100 queries).