We have a governor limit in Apex, which is, we cannot fetch more than 50K records in a single transaction.

What is the solution when you want to work with more than 50K records in a single transaction? The answer is Batch Apex.

Based on what I have seen, a lot of folks get confused with Batch Apex. This is my attempt to make you understand Batch Apex in very simple terms.

Batch Apex programming is very similar to eating Pizza 🍕🍕🍕

Yeah, you heard me right!

Can you eat a large pizza as a single piece without slicing it down into pieces?

No, you cannot.

Then what's the solution?

You will slice it down into small pieces and you will feast on it.

Likewise, when we more than 50K records we will slice them out into small chunks called Batches (chunks).

Regarding the batch(chunk) size either you can specify the batch size or you can leave the default value which is 200 records per batch.

Let's get a bit technical.

If you want to convert normal Apex to Batch apex your class needs to implement the interface Database.Batchable<SObject>.

Interface is like a contract between two parties. The Interface will give you only method signatures and you need to provide body to those methods.

When your class implements an Interface then your class you need to implement all the methods of the interface.

Remember I told ya! Interfaces are like contracts.

As a part of that, we need to override three methods

  1. start()
  2. execute()
  3. finish()
Am not focusing on the parameters of the methods

Just like how you eat slice after slice when you have your pizza. One after the other each and every chunk enters the execute() method and it gets executed.

By default the state of the variables is not stored in batch classes and you need to implement Database.Stateful in case you want to store the state.
By default you cannot make a REST API callout from your Batch Apex. You need to implement Database.AllowsCallouts to be able to make REST API callouts

The finish method also gets invoked once towards the end of invoking all the batches(chunks).

Just like how you prefer to pay the check after enjoying your large pizza slice after slice :p

Okay now am gonna go and have a pizza! 🤤🤤