Batch APEX

Dealing with Bulk data in Salesforce !

Salesforce relies on data processing techniques to ramp up sales, to strategize marketing efforts and to provide better customer support solutions.  But the Data around which the whole thing revolves can range from a tiny kilobyte to a huge zettabyte. Processing such a massive amount of data requires robust metadata functionality. To meet this requirement, Salesforce came up with Batch apex class. It is used to build complex and high time-consuming processes in Salesforce.

How does apex batch deal with Huge data?

Batch apex internally fetches all the data and divides it into smaller countable chunks and then processes them one by one.

How to call a batch class?

Your_class_name context_variable = new Your_class_name();


How to use apex Batch?

Prerequisites: Interface, Abstraction

Salesforce has defined an interface named Database.batachable which is required to be implemented by any class to become a batch class.

Once done, the whole process of data processing in the apex batch is divided into three parts.

Start, Execute and Finish.

Start – It is a method (of Database.batachable interface) which takes context variable (initialized while calling the batch class) as input and returns smaller chunks of retrieved data through querylocator class. It also retrieves all the data on which processing is to be performed. Querylocator in start method can fetch up to 50 million records on one go.

Syntax: public (Database.QueryLocator) start(Database.BatchableContext context) {}

Execute – It is a method (of Database.batachable interface) which takes context variable and a list of smaller chunks of data from the start method and processes them. Size of the chunked list depends on the value of variable input while calling the batch class. It can range from the group of 1-2000 whereas 200 is the recommended size.

Syntax: public void execute(Database.BatchableContext context, list<Sobjects>){}

Finish – It is a method (of Database.batachable interface) which takes the context variable as input. It is responsible for dealing with post-processing activities like sending confirmation emails of job completion, updating a record in the database for error and success notifications and so on.

Syntax: public void finish(Database.BatchableContext context){}

Note – If the data is more than 50 million records then admins may have to either wait for the next iteration of the batch to fetch data or build logic to call another class through batch chaining (We will learn in the upcoming blogs) from finish method which works on the remaining data.

Happy batching!