+ Start a Discussion
Learning Apex (OOP)Learning Apex (OOP) 

Reasoning process to move SOQL-Queries and DML statement outside a 'for' loop

I have an apex trigger which does not align (AT ALL!) with Salesforce "Best Practice" of never having queries and/or DMLs inside a 'for' loop.

I know this theory but, as I am new to coding, I need to break the ice and put this theory into practice (for the first time of my life) and I would like to ask if there is a "Best approach" to doing precisely that (moving SOQL-queries and/or DMLs outside the 'for' loop on 'Trigger.new', or for that matter, to move them from any loop).

Is there any approach, guide, video that could teach me to learn this "optimization process" of my code?

Below, here is my trigger (but please, do not give me the whole solution yet/inmediately, I am looking for a guide for me to try putting it into practice); thank you!:

==>This trigger adds Team Members to an Opportunity upon creation of that new Opportunity:
trigger OwnerManager on Opportunity (after insert) {
    for(Opportunity opp : Trigger.new){
        //Get opp Owner.Manager info
        Opportunity oppWithManagerInfo = [SELECT Id,
                                          Owner.ManagerId
                                          FROM Opportunity
                                          WHERE Id = :opp.Id];
        //Get opp Owner direct dependents
        List<user> directDependents = [SELECT Id
                                       FROM user
                                       WHERE ManagerId = :opp.OwnerId
                                       LIMIT 1];
        //Create Opportunity Team Role
        if (oppWithManagerInfo.Owner.ManagerId != null) {
            OpportunityTeamMember otm = new OpportunityTeamMember();
            otm.UserId                = oppWithManagerInfo.Owner.ManagerId;
            otm.OpportunityId         = opp.Id;
            otm.TeamMemberRole        = 'Sales Manager';
            insert otm;
            //Create another Opportunity Team Role with directDependent
            if (directDependents.size()>0){
                OpportunityTeamMember otm2 = new OpportunityTeamMember();
                otm2.UserId                = directDependents[0].Id;
                otm2.OpportunityId         = opp.Id;
                otm2.TeamMemberRole        = 'Sales Rep.';
                insert otm2;
            }
        }
    }
}

 
Gokula KrishnanGokula Krishnan
Hi Ted,

First, You need to learn collections in salesforce.
Collectionhttps://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections.htm

For your above program, you can use List<>. Instead of doing insert operation in the line 26, you need to add the values in the List, and outside the loop you need to Insert the list values.

I know the solution for your program, but i'm not going to give, please refer the below link 

Referencehttps://trailhead.salesforce.com/en/modules/apex_triggers/units/apex_triggers_bulk

Thanks,

If it helps you, please mark is as best answer, so it will be helpful for other developers.
 
Sandeep WaliaSandeep Walia
Hi,

Initially working on the salesforce platform can be a little bit daunting because of the many constraints that one has to face while coding on it. You can follow the below reources to know more about coding best practices: 
  1. I would advice you to first and foremost read about the various Execution governor limits (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm). This will give you a very basic idea as to what you can and cannot do on the platform. It also mentions the reasons as to why these limits have to be enforced.
  2. Once you know the reasons about the constraints, you can read this article whichexplains the bulkification of code (https://developer.salesforce.com/page/Best_Practice%3A_Bulkify_Your_Code) and broadly answers your above question as to why you cannot write an SOQL query or DML operation in a for loop.
  3. Always have the Official developer guide (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dev_guide.htm) handy for reference while development. There is also a pdf (https://resources.docs.salesforce.com/sfdc/pdf/salesforce_apex_language_reference.pdf) version in case you want to access it offline.
  4.   Here is a list of blogs that you should follow:
    1. SFDC 99 (http://www.sfdc99.com) : One of the best blog for beginners. Created by Salesforce MVP David Liu
    2. Salesforce Tutorial (http://www.salesforcetutorial.com/) : This blog will help you understand the basic concepts of Salesforce.
    3. Official Salesforce Blog (https://developer.salesforce.com) : the official blog of Salesforce.com, keeps you up to date with the latest features of Salesforce.
    4. The Awesome Salesforce Repo on Github (https://github.com/mailtoharshit/awesome-salesforce)  : Contains info  and links to most of resources that you would require for Salesforce platform. You can also see the list of all the popular blogs in this repository. 
  5. My final two cents would be that always make sure that 'Coding triggers and apex classes  should be the last option' as there are many awesome tools on Salesforce such as workflows,Process Builders and Flows that can solve most of the problems.                                         
Do post on this thread in case you have any further query.

Hope this helps,
Sandeep