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
Aishwarya LondheAishwarya Londhe 

How to remove soql query from for loop

Set<Id> accId= new Set<Id>(rootParentIdSet);
for(Integer counter = 0; counter < 7; counter++) {
                 Map<Id, Account> accMap = new Map<Id, Account>([Select Id,ParentId from Account
                 where ParentId In :accId);
              if(accMap != null && !accMap.isEmpty()) {
                    accId= accMap.keySet();
                    accIdSet.addAll(accId);
               }
            }
AbhinavAbhinav (Salesforce Developers) 
I don't see any dependency of loop variable on your query.It will fetch the same result whether used inside or outside the loop.

Not sure why you have accId= accMap.keySet(); as at firts place you are using accId in your query.
 
Divya VorugantiDivya Voruganti
Hi Aishwarya,
You can simply add  Map outside the for  loop or else you can  take list also.
If your requirement is to collect all account Id's which have parent account, You can try below code and check once.

Set<Id> accId= new Set<Id>(rootParentIdSet);
list<Account> lstAccs =[Select Id,ParentId from Account where ParentId In :accId]; // retrieving accont records where parent id in accId.
Set<Id> accIdSet= new Set<Id>();
for(Account acc: lstAccs ){ // iterating allaccounts one by one.
         accIdSet.add(acc.id); //every account id is adding to set.
}
 
If my answer is helpful mark it as best answer.
Thanks & Regards,
Divya.
Divya VorugantiDivya Voruganti
Hi Aishwarya,

If the above one is not your requirement post your exact requirement again.

Thanks & Regards,
Divya.
Aishwarya LondheAishwarya Londhe
thank you Divya !
Â