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
Lakshmi SLakshmi S 

Can we use SOQL Query in inner for loop ?

Hi Team,

Can we use SOQL Query in inner for loop ?

EX:
for(Opportunity opp : Trigger.New){
        
        for(User usr : [Select id from user where name =:opp.Manager__c]){

            opp.Manager_Lookup__c = usr.Id;

        }
    }
Please advise.

Thanks,
Lakshmi S.
 
Harsh P.Harsh P.
Hi Lakshmi,

This is regarding the apex Best Practices that we must follow at the time of development.
We can use but it will hit the governer limit.So it is best to avoid the SOQL inside the inner FOR loop.
To clear the concept use the below link:

https://developer.salesforce.com/page/Best_Practice%3A_Avoid_SOQL_Queries_Inside_FOR_Loops

If it helps mark as Best Answere to help other peoples.

Thanks !
Ajay K DubediAjay K Dubedi
Hi Lakshmi,
No, the SOQL query in for loop did not consider as best practice. So please go to for below link:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_bestpract.htm
https://developer.salesforce.com/page/Apex_Code_Best_Practices
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
Lakshmi SLakshmi S
Hi Ajay & Harsh,

Thanks for your reply.

Thanks,
Lakshmi S