How to Address the “Too Many DML Statements: 151” Error in Salesforce with Code Examples
The “Too Many DML Statements: 151” error in Salesforce is another type of governor limit error. It occurs when an Apex transaction executes more than 150 Data Manipulation Language (DML) operations. DML operations include commands like insert, update, delete, and upsert. Salesforce sets this limit to prevent a single transaction from overusing shared resources.
Understanding the Error
- DML Governor Limit: The limit of 150 DML statements per transaction applies regardless of the number of records affected by each DML operation.
- Transaction Context: A transaction starts when an Apex operation begins and ends when it completes, encompassing all the operations performed in-between, including triggers, workflow rules, etc.
Common Causes
- DML Inside Loops: The most common cause is performing DML operations inside loops, which quickly exhausts the limit.
- Multiple Trigger Firings: If multiple triggers across different objects are executing DML operations, they collectively count towards this limit.
Code Examples and Solutions
Bad Practice: DML Inside a Loop
List<Account> accountsToUpdate = [SELECT Id, Name FROM Account WHERE Name = 'OldName'];
for(Account acc : accountsToUpdate) {
acc.Name = 'NewName';
update acc; // This is a bad practice
}In the above example, the update DML operation is inside the loop, which means it executes as many times as there are accounts, potentially exceeding the limit.
Good Practice: Bulkify Your Code
List<Account> accountsToUpdate = [SELECT Id, Name FROM Account WHERE Name = 'OldName'];
for(Account acc : accountsToUpdate) {
acc.Name = 'NewName';
}
update accountsToUpdate; // Bulk update outside the loopIn this improved example, the DML operation is outside the loop. No matter how many accounts are processed, it counts as only one DML statement.
Additional Solutions
- Use Collections: Aggregate data into lists, sets, or maps, and perform DML operations on these collections outside of loops.
- Optimize Logic and Workflow: Review the logic in triggers and classes to ensure DML operations are only executed when necessary.
- Batch Apex: For processing large data sets, use Batch Apex, which breaks the operation into smaller batches, each with its own governor limits.
- Testing and Monitoring: Use Apex test methods to simulate different data volumes and scenarios, ensuring your code respects governor limits.
Final Thoughts
Understanding and adhering to Salesforce’s governor limits is crucial for writing efficient, scalable Apex code. The key is to process data in bulk and avoid DML operations inside loops.
Enroll for a demo at CRS Info Solutions to explore our Salesforce course for beginners, designed for in-depth CRM admin and development training. Start your Salesforce journey today!

