function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Anas AlamourAnas Alamour 

Batch Apex - Too many DML statements: 151

I have Batch Apex named "PardotLeadFieldsUpdateBatch" , where : 
1- Start method : The query retirves 49820 Lead record
2- Execute method : I am updating the Lead records as following 
List<Database.SaveResult> updateLeadResult = Database.update(updatedLeads, false);
where updateLeadResult is list defined as following : 
List<Lead> updatedLeads = new List<Lead>();
3- FInish method : I am logging any update error in this method
4- I am setting the batch zise to 200 as following :
Database.executeBatch(new PardotLeadFieldsUpdateBatch(),200);
So , based on the batch size "200", and number of records "49820" , the execute method will be running 249 times. 
Recntly, in some days , not all days , i am getting the following error : 
Apex script unhandled exception by user/organization: 
xxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxx
Failed to process batch for class 'PardotLeadFieldsUpdateBatch' for job id 'xxxxxxxxxxxxxxxxxx'
caused by: System.LimitException: Too many DML statements: 151
Trigger.LeadEncrypt: line 5, column 1
where "LeadEncrypt" is apex trigger on Lead object that update filed on Lead record after insert or update as following :
trigger LeadEncrypt on Lead (after insert, after update) {
// Update field in Lead Object 
}
What do you think the reason for my error : "Too many DML statements: 151" ? Is that becuase my batch size is 200 ? Does that mean , on each time the execute method is runnig , there are 200 update operations on lead object,and that hits the apex limit 150 for DML operations as mentioned in the following link :
https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_apexgov.htm
But in my code , in one batch , i am inserting all the leads in a list and apply the database update operation on that list , not on 200 record individually. If i reset the batch size to 150 or 100 , does that will fix the error ? or there are another reason for this error ? 

Please advise.

VinayVinay (Salesforce Developers) 
Hi Anas,

It would be difficult to say why it is throwing too many DML error unless we debug and narrow down the scenerio.  However below are few details and check points.

Salesforce only allows 150 DML statement in a transaction if the DML statement exceeds the allowed governor limit then the logic throws “Too many DML statement: 151” error.  Below are check points to avoid above error.
  • Code bulkification
  • No DML in For loop
https://salesforcean.blogspot.com/2017/10/batch-apex-governor-limits-best.html

Please mark as Best Answer if above information was helpful.

Thanks,