I have a batch class

global Database.queryLocator start(Database.BatchableContext bc){

    return Database.getQueryLocator('Select Field1__c, Field_2 from  Object1__c where Status__c in (\'New\', \'Retry\') );

global void execute (Database.BatchableContext BC, List<Object1__c> object1List){

    for(Object1__c  object1 : object1List){
        List<Account> account = [select Id from Account where SCH_ID__c=:object1__c.Field1__c];

Here Field1__c is not a lookup field. I would like to understand if I can move the query out of the for loop without the use of a map. i tried the use of teh following but it needs a reference field to work


  • 1
    What's the relationship between Account and Object1__c? Or is it just the Field1__c is some text linked to Account and Why you don't want to use a map is there any specific reason to avoid using map. What the further logic in the for loop with account list? – RCS Apr 18 '18 at 10:32
  • Using a Map is a standard bulkification pattern and you don't have to have a lookup field in place to apply it. – David Reed Apr 18 '18 at 10:54
  • Could you clarify if the query in the loop always returns one result or can return many results? You can replace a Map with a List and just loop through to find the Account you're looking for, but there's no good reason to do that. – IllusiveBrian Apr 18 '18 at 12:41

Considering Field1__c has id values, i.e. 15 or 18 digit Salesforce Ids, then you can create a Set<Id> and feed it to your SOQL. You could do something like

Set<Id> schIds = new Set<id>();
for(Object1__c  object1 : object1List){
if(shcIds.size() > 0) {
    List<Account> account = [select Id from Account where 
    SCH_ID__c IN: schIds];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.