+ Start a Discussion
Kumaresan.ManickamKumaresan.Manickam 

What are the scenario to use SOQL For loops in Apex?

Dear Community,

I understand that SOQL for loops greatly helpful to avoid heap size problems while handling large set of records as it works via processing batch of request at a runtime instead of pulling whole large data at a time. But Is it best to use same SOQL for loop queries multiple times in the apex when i want to iterate a list more than once in the same context? I was concerned about performance problem if i repeat same queries more than once. Any suggestions & best practices would be very helpful

Thanks
Deepali KulshresthaDeepali Kulshrestha
Hi Kumaresan,

If you get all the records of an object through SOQL in a List then you can you iterate a list more than once in the same context. There is no performance problem
to repeat the same queries more than once.

Attachment[] records = [SELECT Body FROM Attachment];
for(Attachment record: records) {
    record.Body = encrypt(record.Body);
}
update records; 

Few important Governor Limits in Salesforce

In one transaction, we can use a maximum of 100 SOQL queries.
In one transaction, we can use a maximum of 20 SOSL queries.
In one transaction, we can use a maximum of 150 DML statements.
In one transaction, we can fetch a maximum of 50k records in SOQL.
In one transaction, we can fetch a maximum of 2k records in SOSL.

But you can use Nested "For" Loops since it decreases performance. To avoid nested loop then you used Map 

public class MapEx {
    
    public static void createMap(){
        try{
           List<Account> accountList = [select id from Account  ];
            
            set<Id> accIds =new set<Id>();
            for(Account acc:accountList){
                accIds.add(acc.Id);
            }
            System.debug('accIds-> '+accIds);
            
            List<Contact> contactList  = new List <Contact>();
            contactList = [select id,AccountId from Contact where AccountID IN : accIds ];
            
            Map<Id,long> accId_contactMap = new Map<Id,long>();
            
            for(Contact con:contactList){ // accouuntId - nuber of related contact
                if(accId_contactMap.ContainsKey(con.AccountId)){
                    long count = accId_contactMap.get(con.AccountId);
                    accId_contactMap.put(con.AccountId , count+1);
                }
                else{
                    accId_contactMap.put(con.AccountId , 1);
                    }
            }
            
            System.debug('accId_contactMap-->'+accId_contactMap);
        }catch(Exception e){
            System.debug('get exception on line-->'+e.getLineNumber()+' error is-->'+e.getMessage());
        }
    }

}



I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com