Delete all records in a large Salesforce table looping through a batch of 10,000 records

Delete all records in a large Salesforce table looping through a batch of 10,000 records

Go to Salesforce Setup Menu > Platform Tools > Custom Code > Apex Classes


Create a new class and write below code:

public with sharing class DeleteRecordsBatch implements Database.Batchable<sObject>{

    public static Database.QueryLocator start(Database.BatchableContext Context) {
        System.debug('Batch job is starting');
        return Database.getQueryLocator('Select id from Program');
    }
    
    public static void execute(Database.BatchableContext context,List<Program> scope){
        try{
            System.debug('Batch job is executing');
            delete scope;
        }
        catch (Exception e){
            System.debug(e.getMessage());
        }
    }
    
    public static void finish(Database.BatchableContext context){
        System.debug('Batch job is completed');
    }

}

Note: In above query, I'm deleting "Program" table. replace it with your own table.



Now, save the Class and open Salesforce developer Console.

Execute our class "DeleteRecordsBatch" created above in an anonymous window.