Skip to content

Too many DML statements: 151

The DML limit counts statements, not records, and a savepoint in a loop spends two at a time. What actually counts toward 150 and how to get back under it.

TL;DR

  • Apex allows 150 DML statements per transaction. The number is the same for synchronous and asynchronous code, so moving work to a Queueable gives you a fresh 150, not a bigger one.
  • The limit counts statements, not records. update accounts; on a list of 200 costs one statement. The same 200 updated inside a loop cost 200.
  • Records have their own budget: 10,000 rows processed by DML per transaction. Bulkifying fixes the statement count without touching that one.
  • The list of operations that count is longer than most people assume. Database.setSavepoint, Database.rollback, System.runAs, Database.convertLead, Approval.process, Database.emptyRecycleBin and EventBus.publish for publish-after-commit events all spend from the same 150.
  • Like the SOQL limit, the line in the stack trace is just where the budget ran out. Limits.getDmlStatements() tells you who spent it.

What You'll Learn

  • Exactly which operations count toward the 150
  • Why a per-record savepoint pattern burns the budget twice as fast
  • The collect-then-write pattern, in Apex and in Flow
  • How to tell whether the problem is your code or the automation around it
  • Why async does less for this limit than for SOQL

The Problem

The error usually turns up the first time somebody runs a bulk job against code that was only ever exercised from the UI. One record at a time, a loop that saves each record costs a handful of statements and nobody notices. A data load of 200 records turns the same loop into 200 statements, and the transaction dies at 151.

The other common route is quieter. Each piece of automation on an object writes a few records of its own, every one of them correct in isolation. Add a trigger here, a record-triggered flow there and a managed package on a related object, and a save that used to cost 40 statements now costs 151.

Both look the same in the log: a System.LimitException pointing at a line that writes one record.

Common questions this article answers:

  • Does updating a list count as one statement or one per record?
  • Why does my error handling code use up the DML limit?
  • If I move this to a Queueable, does the limit go away?

Quick Answer

Apex allows 150 DML statements per transaction, and the limit is the same in synchronous and asynchronous contexts. A statement is one call, so insert, update, upsert, delete, undelete and merge on a list cost one each regardless of list size, up to the separate limit of 10,000 rows per transaction. The usual cause is DML inside a loop, and the fix is to add records to a List inside the loop and write the list once after it. Savepoints, rollbacks, System.runAs, lead conversion, Approval.process, Database.emptyRecycleBin and EventBus.publish for publish-after-commit platform events also count, so per-record savepoint patterns use two statements per record. In Flow, the equivalent mistake is a Create or Update Records element inside a Loop. When the budget is spent before your code runs, Limits.getDmlStatements() at the entry point will show it, and the fix is to consolidate writes across the automation on that object.

What counts toward the 150

The Apex Developer Guide lists the calls that count. About half of the list is not what people think of as DML:

Counts as a DML statement Notes
insert, update, upsert, delete, undelete, merge Both the statement form and the Database.* method form
Database.setSavepoint One per savepoint created
Database.rollback One per rollback
System.runAs Mostly a test concern, but it counts
Database.convertLead One per call, not per lead
Approval.process Also counts toward the 10,000 row limit
Database.emptyRecycleBin Also counts toward the 10,000 row limit
EventBus.publish Only for platform events set to publish after commit

Platform events set to publish immediately have their own separate limit of 150 EventBus.publish calls, so they do not draw on the DML budget, but a loop that publishes one event per record will hit that ceiling instead.

What does not count: SOQL and SOSL (they have their own limits), field assignments in a before trigger (the platform saves those records without a statement from you), and DML in a separate transaction started by @future, a Queueable or a Batch execute.

The figure follows one save of 200 records through three versions of the same trigger. Switch between them to see where the statements go.

One save of 200 records, written three ways. Switch between them and point at, or tap, a hop.
Data load200 recordsYour triggerApexDatabase150 statementsAutomationFlows, packages200 recordsupdate x 200LimitException

Statements, not records

The budget is 150 DML statements per transaction. One update on a list costs one, however many records are in it.

Red hops are where the budget runs out. Other automation on the same save spends from the same 150.

The savepoint trap

Careful developers hit this one, because it comes from trying to handle errors properly.

// Two DML statements per record before any real work happens
for (Order__c ord : orders) {
    Savepoint sp = Database.setSavepoint();
    try {
        update ord;
        insert new Order_Log__c(Order__c = ord.Id);
    } catch (DmlException e) {
        Database.rollback(sp);
    }
}

Per record that is a savepoint, an update, an insert and, on failure, a rollback. Three statements when the record saves and four when it fails, so the loop dies somewhere between record 38 and record 51. The intent is reasonable: let one bad record fail without losing the rest. The platform already offers that through partial success, at one statement per object:

List<Database.SaveResult> results = Database.update(orders, false);

List<Order_Log__c> logs = new List<Order_Log__c>();
for (Integer i = 0; i < results.size(); i++) {
    if (results[i].isSuccess()) {
        logs.add(new Order_Log__c(Order__c = orders[i].Id));
    } else {
        System.debug(LoggingLevel.WARN, results[i].getErrors());
    }
}
insert logs;

Two statements for any number of records. The false argument is allOrNone: failed records come back in the results with their errors, and the successful ones are saved. The results list is in the same order as the input list, which is why indexing by i works.

Collect, then write

The general fix is the same shape as for SOQL. Never write inside a loop. Build a list, then write it once.

// Fails at 151 once this runs over more than 150 contacts
for (Contact c : contacts) {
    c.Last_Reviewed__c = Date.today();
    update c;
}
// One statement for any list size up to the row limit
for (Contact c : contacts) {
    c.Last_Reviewed__c = Date.today();
}
update contacts;

When one pass produces writes to several objects, keep one list per object and write each at the end. A small unit-of-work class that holds those lists for the whole transaction is the usual next step in a larger codebase, because it stops two classes from each updating Account separately in the same save.

Duplicate entries are the one thing to watch. Adding the same record twice to a list you then update fails with a duplicate id error. Key the pending writes by Id in a Map<Id, SObject> when several code paths may touch the same record.

The Flow version of the same mistake

Flow builders hit this limit through a Create Records or Update Records element placed inside a Loop. Each pass through the loop is a separate write. The fix is the Flow equivalent of the Apex pattern: use an Assignment inside the loop to add the record to a collection variable, then one Update Records element after the loop that takes the collection.

Record-triggered flows have one more consideration. Flow batches interviews that start from the same bulk save, so a well-built record-triggered flow handles 200 records with a small number of writes. A loop with an Update element inside undoes that batching.

When the budget is gone before your code runs

Instrument the entry point before rewriting anything:

System.debug('DML used: ' + Limits.getDmlStatements() + ' of ' + Limits.getLimitDmlStatements());
System.debug('DML rows: ' + Limits.getDmlRows() + ' of ' + Limits.getLimitDmlRows());

If your trigger starts with 140 statements already spent, rewriting it will not help. The debug log's cumulative limit usage section shows the same numbers, and the execution tree above it shows every trigger, flow and package that ran.

Three things tend to be behind a large upstream spend:

  1. Several triggers or flows on one object, each updating the same related record. Five pieces of automation that each update the parent Account cost five statements and fire Account automation five times. Consolidate them so the parent is written once.
  2. Recursion. An update trigger that updates its own object fires itself again. A static guard that tracks which ids have already been processed stops the repeat writes.
  3. Write-backs that change nothing. An update issued when no field value changed still costs a statement and still fires automation. Compare old and new values and only add the record to the list when something differs.

Async gives you a new bucket, not a bigger one

The SOQL limit doubles from 100 to 200 in asynchronous Apex. The DML limit does not change: it is 150 in both. Moving work to a Queueable helps only because the Queueable runs in its own transaction with its own 150.

That is useful for genuinely deferrable work, such as writing an audit trail after the save completes. It does nothing for a loop that issues one statement per record, which will fail in the Queueable just as it failed in the trigger once the data is large enough.

Frequently Asked Questions

Q: Does a DML statement on a list of 200 records count as one or 200?

A: One toward the statement limit, and 200 toward the separate limit of 10,000 rows processed per transaction. That split is the whole reason bulkifying works.

Q: Can Salesforce raise the 150 limit?

A: No. It is a hard governor limit. The only ways back under it are fewer statements per transaction or splitting the work across transactions.

Q: My test class fails with this error but production does not. Why?

A: Usually test setup. Test methods often create data record by record in loops, and System.runAs counts as a statement as well. Test.startTest() resets the limits for the code under test, so build data in bulk before startTest() and put only the operation you are testing between startTest() and stopTest().

Q: Does publishing a platform event count?

A: It depends on the event's publish behaviour. EventBus.publish for events set to publish after commit counts as a DML statement. Events set to publish immediately have a separate limit of 150 publish calls. In both cases, publish a list of events in one call.

Q: Is Database.update(records, false) slower than update records?

A: Not meaningfully. It is the same single statement, with failed records returned to you instead of rolling back the batch. It is usually the right choice for integrations and data loads, where one bad record should not stop the rest.

Key Takeaways

  • 150 DML statements per transaction, synchronous and asynchronous alike. Async gives you a fresh 150, not a larger one.
  • Statements are calls, not records. One update on a list costs one statement, up to 10,000 rows.
  • Savepoints, rollbacks, System.runAs, lead conversion and approvals all count. Per-record savepoints spend the budget two or more statements at a time.
  • Use partial success (Database.update(records, false)) when one bad record should not sink the rest.
  • Write each object once per transaction. In Flow, keep Create and Update elements out of loops.
  • Measure before rewriting. Limits.getDmlStatements() shows whether the budget is yours or upstream.

What's Next?

Recommended Reading:

Action Items:

  1. Add Limits.getDmlStatements() logging at the start and end of the failing operation.
  2. Search the codebase for insert, update and Database.setSavepoint inside for loops.
  3. Open each record-triggered flow on the affected object and look for Create or Update elements inside a Loop.

Resources & References

Responses

Checking your session.

Loading responses.