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
rishi jaykar 1rishi jaykar 1 

How can we access variable in all method which is start, execute, finish?

You can implement the Database.Stateful interface within your Apex Batch Job to make your instance variables across the complete execution of the Batch Job.

If you specify Database.Stateful in the class definition, you can maintain state across these transactions. When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions. Maintaining state is useful for counting or summarizing records as they’re processed. For example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the opportunity amounts as they were processed.

Sample code below leverages the Summary variable across every transaction of the Batch Job and holds the summary of the total records processed.
global class SummarizeAccountTotal implements 
    Database.Batchable<sObject>, Database.Stateful{

   global final String Query;
   global integer Summary;
   global SummarizeAccountTotal(String q){Query=q;
     Summary = 0;

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(query);
   global void execute(
                Database.BatchableContext BC, 
                List<sObject> scope){
      for(sObject s : scope){
         Summary = Integer.valueOf(s.get('total__c'))+Summary;

global void finish(Database.BatchableContext BC){
Refer the following article to know more about using Database.Stateful -

Please mark this thread as SOLVED and answer as the BEST ANSWER if it helps address your issue.

Has this issue been addressed for you? If yes, please mark the thread as SOLVED and answer as the BEST ANSWER.