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
Ravi23Ravi23 

Refine the query when we search in batch Class

Hi All,

         Below is my Batch class. Is that always we require to pull complete records in databse in query field or can we filter using where condition. If we can filter can some one help me on this.

global class batchContactAccountNameUpdate implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, AccountId  FROM Contact ';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<Contact> scope) {
         for(Contact c : scope)
             
         {
             if(c.AccountId==null){
             
             c.AccountId = '0011900000BiZzn';            
         }
         }
         update scope;
    }   
    
    global void finish(Database.BatchableContext BC) {
    }
}
sandeep unnikrishnansandeep unnikrishnan
you can put a where clause on your query
String query = 'SELECT Id, AccountId  FROM Contact where email !=null';//just an example


you can control the batch size while invoking this class like below
 
Database.executeBatch(new batchContactAccountNameUpdate (), batch size);// batch size can be any number

 
Ravi23Ravi23
Hi Sandeep I made the query like this

String query = 'SELECT Id, AccountId,Type__C  FROM Contact where Type__c=:Asian Entities';

And I am not getting error in code but when I run the batch class I get unexpected token Entities
sandeep unnikrishnansandeep unnikrishnan
Hi can you pls try :-
 
String query = 'SELECT Id, AccountId,Type__C  FROM Contact where Type__c=\'Asian Entities\'';

 
Ravi23Ravi23
Hi Sandeep,

               This time no error when I run the batch but not even one record was processed in the batch. Which is indicating the query was not realized.
sandeep unnikrishnansandeep unnikrishnan
SELECT Id, AccountId,Type__C  FROM Contact where Type__c='Asian Entities'

can you run the above query from dataloader/devconsole and see what is being returned ?