+ Start a Discussion
Luke Higgins 22Luke Higgins 22 

DML Exception error on batch class

I'm trying to update a field on ts2__Placement__c records that meet the criteria. I believe it's because I am doing a DML statement within a for loop. How do I avoid this and get the same results?
public class plc2WeekAudit implements Database.Batchable<sObject>, Database.Stateful {
    List<Change_Request__c> plcList = [SELECT Related_Placement__c FROM Change_Request__c WHERE End_Date__c != null AND Related_Placement__r.ts2__Status__c ='Active' AND Related_Placement__r.ts2__End_Date__c < LAST_N_MONTHS:1];
    Set<String> duplicatePlc = new Set<String>();

    public Database.QueryLocator start(Database.BatchableContext bc) {
        for(Change_Request__c item : plcList){
        System.debug('the size is : ' +duplicatePlc.size());

        return Database.getQueryLocator('SELECT Id,ts2__Status__c FROM ts2__Placement__c WHERE Id IN :duplicatePlc');    
    public void execute(Database.BatchableContext BC, List<ts2__Placement__c> returnedPlcs){
        for(ts2__Placement__c plc : returnedPlcs){
            plc.ts2__Status__c = 'Inactive';
        update returnedPlcs;
    public void finish(Database.BatchableContext BC){

Prangya JenaPrangya Jena
Hi Luke,

There is no DML inside for in your code. Can you tell me what is the dubg in line 10 is giving?
Luke Higgins 22Luke Higgins 22
The debug line is giving the correct batch size that I'm using which is "the size is : 20"
ShirishaShirisha (Salesforce Developers) 
Hi Luke,


Can you please avoid using the DML statements inside the for loops which cause the issues like hitting the governor limits when dealing with the huge data.

Also,please follow the best practices as mentioned in the below documentation which has an example as well:


Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Warm Regards,
Shirisha Pathuri