[SalesForce] Batch Job Error: Too Many queries: 50001

public class UpdateBrandBatch implements Database.Batchable<sObject>, Database.Stateful {
    final List<SObject> records = new List<sObject>();
    final string query1, query2;

    public updateBrandBatch(){
        query1 = 'select id, brand__c from account';
        query2 = 'select id, brand__c from contact';
    }

    public Iterable<sObject> start(Database.BatchableContext BC) {   
        records.addAll(Database.query(query1));
        records.addAll(Database.query(query2));
        return records;
    }    

    public void execute(Database.BatchableContext BC, List<sObject> scope) {   
        for (sObject c : scope) {
            c.put('brand__c', 'MyBrand');
        }
        update scope;
    }    

    public void finish(Database.BatchableContext BC) { }   

}

Calling this batch from anonymous window using :

Database.executeBatch(new UpdateBrandBatch(), 20);

even though i enter batch size as 20, still getting the exception. There are some 20 million records of account and about 30 million contacts

Thanks

went through question # 60164 here in SOF and as per suggestion tried reducing the batch size but that didnt help.

Best Answer

You can't query more than 50,000 rows in your start method. You need a QueryLocator. In practice, this probably means you'll need to run your batch twice, once by accounts and then once by contacts. Probably something like this:

public class ProcessRecords implements Database.Batchable<SObject> {
    public String[] queries = new String[] { 'select brand__c from account', 'select brand__c from contact' };
    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator(queries.remove(0));
    }
    public void execute(Database.BatchableContext context, SObject[] records) {
    // Do processing here
    }
    public void finish(Database.BatchableContext context) {
       if(!queries.isEmpty()) {
          Database.executeBatch(this, 20);
       }
    }
}

For unit testing, you may need to call your methods directly instead of trying to execute the batches using Test.stopTest(), to avoid chaining errors.