You are here:
ApexGuru Antipattern: SOQL in a Loop (One Hop)
The SOQL query is placed in a method in one class and the loop that invokes this method is in a different class. This structure leads to excessive SOQL queries, potentially hitting governor limits. Repeated query execution across class boundaries causes performance bottlenecks. Refactor the code to batch SOQL queries outside the loop, even if they’re spread across multiple classes.
Scope
Detection only
Detection Example
apex
public class FirstClass {
public static List<Contact> getContactsForAccount(Id accId) {
return [SELECT Id, Name FROM Contact WHERE AccountId = :accId LIMIT 5];
}
}
public class SecondClass {
public static void processAccounts() {
List<Account> accounts = FirstClass.getAccounts();
for (Account acc : accounts) {
List<Contact> contacts = FirstClass.getContactsForAccount(acc.Id);
// Process contacts
}
}
}
