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
MokshadaMokshada 

batch class to delete leads older than 3 months.

I want to write a batch class to delete leads whose last modified date is older than 3 months.
can anyone help?
Best Answer chosen by Mokshada
CharuDuttCharuDutt
Hii Mayuri DeshMukh
Try Below Code
global class Batch_DeleteLeads implements Database.Batchable <sObject> {

   String query = 'SELECT Id FROM lead WHERE LastModifiedDate < LAST_N_DAYS:90;
    global Database.QueryLocator start(Database.BatchableContext bc){
         
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext bc,List<lead> batch){
    list<lead> LeadToDelete = new list<lead>();
       for(lead oLead : batch){
       LeadToDelete.add(oLead);
       }
        delete LeadToDelete;
        
    }
    
    global void finish(Database.BatchableContext bc){
     
    }       
}
Please Mark It As Best Answer If It Helps
Thank You!

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi Mayuri,

try with below code.
global class DeleteBatchClass implements Database.Batchable<sObject>{

        // Start Method
        global Database.QueryLocator start(Database.BatchableContext BC){
			string query = 'select id  from lead where LastModifiedDdate < LAST_N_DAYS:90';
			return Database.getQueryLocator(query);
        }
      
      // Execute Logic
       global void execute(Database.BatchableContext BC, List<Lead>scope){
              if(scope.size>0)
		delete scope;
     
       }
     
       global void finish(Database.BatchableContext BC){
            // Logic to be Executed at finish
       }
    }

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​
CharuDuttCharuDutt
Hii Mayuri DeshMukh
Try Below Code
global class Batch_DeleteLeads implements Database.Batchable <sObject> {

   String query = 'SELECT Id FROM lead WHERE LastModifiedDate < LAST_N_DAYS:90;
    global Database.QueryLocator start(Database.BatchableContext bc){
         
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext bc,List<lead> batch){
    list<lead> LeadToDelete = new list<lead>();
       for(lead oLead : batch){
       LeadToDelete.add(oLead);
       }
        delete LeadToDelete;
        
    }
    
    global void finish(Database.BatchableContext bc){
     
    }       
}
Please Mark It As Best Answer If It Helps
Thank You!
This was selected as the best answer
MokshadaMokshada
Hi can you please help in writing test class for this