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
SarahSarah 

How to avoid SOQL query inside for loop

I have the below code and there is a SOQL query inside for loop. I have been instructed to avoid SOQL in the loop as these are invoked for every iteration of the loop. Since i am a beginner in Salesforce i don't know how to implement that. Here's my code where i have advised to use Soql query and condition checking before for loop using a map.

 
if ((isTrgBefore && (isInsert||isUpdate ))){
   for( Item eachitem :newItemList ){
     if(eachItem.WhoId!=Null){
        Schema.SObjectType sobjectType =         eachItem.WhoId.getSObjectType();
        String sobjectName = sobjectType.getDescribe().getName();
        if(sobjectName.equals(UTIL_Constants.SubString)){ 
                    List<Strategy> stg=[select Type from Strategy where Id=:eachItem.WhoId];
                        for(Strategy s:stg){
                            if(s.Type=='Market Strategy' || s.Type=='Market Potency'){
                            eachItem.Strategy__c = eachItem.WhoId; 
                            }
                        }
         }
     }
     setWhatIds.add(eachItem.WhatId);
  }
}

 
AnkaiahAnkaiah (Salesforce Developers) 
Hi Sarah,

Can you explain about your requirement?

As per my understanding, Strategy is custom object and you need to link that object to task.

If yes, try with below code.
 
set<id> whoids = new set<id>();

if ((isTrgBefore && (isInsert||isUpdate ))){
   for( Item eachitem :newItemList ){
     if(eachItem.WhoId!=Null){
	 whoids.add(eachItem.WhoId);
	 }
	 
  }
}

Map<id,Strategy__c> updatemapstra = New map<id,Strategy__c>([select id, Type from Strategy__c where Id=:whoids ]);

for( Item eachitem :newItemList ){
   for(Strategy__c st:updatemapstra.vaules() ){

        Schema.SObjectType sobjectType = eachItem.WhoId.getSObjectType();
        String sobjectName = sobjectType.getDescribe().getName();
        if(sobjectName.equals(UTIL_Constants.SubString)){
		   if(st.id == eachitem.WhoId && (st.Type=='Market Strategy' || st.Type=='Market Potency')){
		   st.Strategy__c = eachItem.WhoId;
		   }
}		

}
}

Update updatemapstra.values();

If this helps, please mark it as best answer.

Thanks!!
SarahSarah
Hi Ankaiah, 

Yes I need to link to that object to task
Can we check that "Market Strategy" And "Market Potency" Condition before the for loop. 
AnkaiahAnkaiah (Salesforce Developers) 
Are you facing any issues?

we need to check the condition with in the for loop.

THanks!! 
Shubham Jain 338Shubham Jain 338
Hi Sarah,

Please find the working code

Set<Id> whoIdSet = new Set<Id>();
    if ((isTrgBefore && (isInsert||isUpdate ))) {
        for(Item eachitem : newItemList) {
            if(eachItem.WhoId != Null) {
                Schema.SObjectType sobjectType = eachItem.WhoId.getSObjectType();
                String sobjectName = sobjectType.getDescribe().getName();
                if (sobjectName.equals(UTIL_Constants.SubString)) {
                    whoIdSet.add(eachItem.WhoId);
                }
            } 
        }
    }
    
    if (whoIdSet.size() > 0) {
        List<Strategy__c> strategyList = [SELECT Id, Type FROM Strategy__c WHERE Id IN :whoIdSet AND (Type = 'Market Strategy' OR Type = 'Market Potency')];
        if (strategyList.size() > 0) {
            for(Strategy__c st : strategyList){
                if (st.Strategy__c != st.Id) {
                    st.Strategy__c = st.Id;    
                }
            }        
            update strategyList;    
        }
    }

Please mark this as the best answer if it helps

Thanks
Shubham Jain