Skip to main content

Salesforce

Batch Class in Apex to Delete Records

Website Design. Developing Programming And Coding Technologies.

Hello Trailblazers,

In this blog post, we’re going to write a batch in Apex to delete the records from the targeted object.

Acceptance Criteria: Write a batch Class in Apex to delete all the account records created in the last 1 year.

Batch Apex is a powerful Salesforce tool that allows developers to create and execute batches of records. It helps you to process up to a million records asynchronously and boosts your organization’s productivity by shortening the time it takes to perform specified activities.

Batch Apex is generally your best option if you have a large number of records to process, such as data cleansing or archiving, etc.

In this example, we’ll also develop a batch class that will delete the account records in batches created in the last 1 year.

So, let’s get started.

Batch Apex to Delete Records:

public class DeleteAccountsBatch implements Database.Batchable<sObject> {

    public Database.QueryLocator start(Database.BatchableContext context) {
        // Query all Account records created in the last 1 year
        Date oneYearAgo = System.today().addMonths(-12); 
                    // OR Date.today().addYears(-1); //Use anyone of them
        String query = 'SELECT Id FROM Account WHERE CreatedDate >= :oneYearAgo';
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext context, List<Account> scope) {
        // Delete the Account records in the current batch
        delete scope;
    }

    public void finish(Database.BatchableContext context) {
        // Execute any post-processing logic if needed
    }
}

 

This batch class, named DeleteAccountsBatch, implements the Database.Batchable interface.

Let’s break down this batch class and understand how it works.

1. Start Method:

The Start Method defines the start of the batch job and returns a Database.QueryLocator to specify the records to be processed.

In this case, it queries all Account records created in the last 1 year.

2. Execute Method:

It processes the records returned by the start method in batches. We need to write down the actual logic that we have to perform.

In the above example, the logic simply deletes the Account records in the current batch.

 

3. Finish Method:

It defines the finish logic of the batch job. This method is executed after all batches have been processed.

You can add any post-processing logic here if needed.

 

After all this, it comes to the execution of the batch class. To execute the above batch, you can use the following Apex script:

DeleteAccountsBatch batchJob = new DeleteAccountsBatch();
Database.executeBatch(batchJob);

This will start the batch job, and it will delete all the Account records created in the last 1 year in batches.

Note that the execute method is called for each batch, so the deletion is done in chunks to avoid hitting governor limits.

Conclusion:

In this way, we developed a batch class that deletes all the records created in the last 1 year.

We can also make it schedulable which we will see in the next part of this blog.

Until then, Stay Tuned!!

 

References:

  1. Batch Apex in Salesforce

  2. Asynchronous Apex in Salesforce

 

You can also read :

1.An Introduction to Salesforce CPQ
2.Salesforce CPQ and its Key Features
3.Unlocking the Power of AI: Einstein for Developers
4.Revolutionizing Customer Engagement: The Salesforce Einstein Chatbot

Thoughts on “Batch Class in Apex to Delete Records”

  1. Hi,

    Thanks so much for this, very helpful when done in sandbox.

    But for the production, I need Test Classes. How can I create code coverage for this class please?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Abhinav Masane

Abhinav Masane is an Associate Technical Consultant at Perficient based in Nagpur. He is a Salesforce Certified Associate and Developer. Abhinav is always keen to learn and explore new technologies.

More from this Author

Follow Us