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
Developer BaseDeveloper Base 

batch updating records

Hello, can you please explain how to make a batch updating of records from one object?

The wrong way is to put the DML statement inside the for loop like this:
list<Account> accs = [Select Id, Name from Account];
for(Account acc :accs) {
acc.Name = 'test';
update acc;
}
This is also a wrong example because we can still exceed the governor limits of updating more than 50000 records at once:
 
list<Account> accs = [Select Id, Name from Account];
for(Account acc :accs) {
acc.Name = 'test';
}
update accs;

I heard that you can do a batch update of 300 records in a list so you don't exceed 50 000 records updated and also you don't hit the too many SOQL queries exception. How to do that though?
Best Answer chosen by Developer Base
Pradhyumn BansalPradhyumn Bansal
Hi Developer Base,

You can update records with Batch from following manner :-

Batch Class :-
 
global class BatchApexExample implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        // collect the batches of records or objects to be passed to execute
         
        String query = 'SELECT Id, Name FROM Account';
        return Database.getQueryLocator(query);
       
         
    }
     
    global void execute(Database.BatchableContext BC, List<Account> accList) {
        
        // process each batch of records default size is 200
        for(Account acc : accList) {       
            // Update the Account Name
            acc.Name = acc.Name + 'any update value';
        }
        try {
            // Update the Account Record
            update accList;
         
        } catch(Exception e) {
            System.debug(e);
        }
         
    }  
     
    global void finish(Database.BatchableContext BC) {
        // execute any post-processing operations like sending email
    }
}

Execute Batch Class :-
--> To invoke a batch class, simply instantiate it and then call Database.executeBatch with the instance:
      MyBatchClass myBatchObject = new MyBatchClass();
      Id batchId = Database.executeBatch(myBatchObject);

--> You can also optionally pass a second scope parameter to specify the number of records that should be passed into the execute method for each batch. 
     Id batchId = Database.executeBatch(myBatchObject, 100);


Code Explaination :- 
1) Here first start method is execute and query object records. With the QueryLocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed and you can query up to 50 million records. 

2) After it passes all the records to accList param in execute method. Then there you update your record's value and after that you update them records. Lets take a example
   --> we assumes query retrive 40200 records and passes it to second parameter of execute method.
   --> In batch apex, here execute method run in small batches/chunks of records. By default it run with 200 records per batch. So here 40200 records will divide in 40200 / 200 = 201 transactions with each transaction process only 200 record.
    --> In this case our query run only one times but DML run 201 times like once per transaction. But we cant get DML governer limits exceed error because every transaction have seperate governer limit range or we can say that for every transaction governer limits are reset. So here every transaction have minimum 150 DML execution Limits.

3)  After the all transacftions/batches are processed finish method will be excuted. Here you do post-processing operations (for example, sending an email).
     --> Each batch Apex invocation creates an AsyncApexJob record so that you can track the job’s progress. You can view the progress via SOQL or manage your job in the Apex Job Queue.
AsyncApexJob job = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID = :batchId ];

For more information go throuh following links :- 
trailhead module :- https://trailhead.salesforce.com/en/content/learn/modules/asynchronous_apex/async_apex_batch
Batch Execution governer limits :- https://developer.salesforce.com/docs/atlas.en-us.224.0.apexcode.meta/apexcode/apex_gov_limits.htm

If you are find this answer useful please mark it as solved answer.

Thank you