1

Hello I need some help moving my SOQL Query outside of my for loop to maintain best practices. I am using the code below to get the most recent opportunity of a selected account and grabbing the owners email:

List<Id> accountIds= new List<Id>();
List<Opportunity> opps=new List<Opportunity>();



for(Account ao:[Select Id,name,(select Id,Owner.Email,name,ownerid from opportunities ORDER BY CreatedDate DESC) from account       
where Id = :A.Id LIMIT 1]) {
   for(Opportunity opp : ao.opportunities)
   {

       System.debug('THIS IS THE MOST RECENT OPP '+opp.Id);
       System.debug('THIS IS THE CONTACT OF THE OPP '+opp.ownerid+opp.Owner.Email);
       Contactidopp = opp.Owner.Email;
   }
}
5

Bad

What we mean when we say do not have a query in a for loop is this:

for (Object o : objects) {
    list<Object2> = [select Id from Object2where RelatedId__c = :o.Id];
}

This is bad because the query runs once per loop which chews through soql query limit of 100.

Fine

for (Object o : [SELECT id FROM Object]) {
    // This is fine
}

This is OK because the query only ever runs once.

Also Fine

List<Object> objects = new List<Object>([
    SELECT Id
    FROM Object
    WHERE Foo__c = 'Bar'
]);

for (Object o : objects) {
    // Code here
}

More info

For a comparison between the two methods, view SFDCFox's answer here.

Maps

This can be expanded further to work with maps which is one of my favorite ways to store data in code as it makes working with it superbly easy if you're working with related objects:

Map<Id, Object> objectMap = new Map<Id, Object>([
    SELECT Id, Parent__c (
        SELECT Id
        FROM Children
    )
    FROM Object
]);

for (object o : objectMap.values()) {
    for (child c : o.children) {
    }
}

// -- OR --
for (Id i : objectMap.values()) {
    object o = objectMap.get(i);
}

// -- OR --
for (OtherObject oo : otherMap) {
    related = objectMap.get(oo.Related__c);

    for (Child c : related.children) {
        // Get crazy with it!
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.