---
schema_version: "1"
id: 4cc3f0820d976ba7f26a7420fc9b6ed1e21ed5e7f076ee5be6266d32a9287373
title: "ApexGuru Antipattern: SOQL in a Loop (One Hop)"
collection: admin
version: current
locale: en-us
portal_url: https://docs.salesforce.com/admin/current/en-us/xcloud/264-0-0/apexguru_antipattern_soql_in_loop_one_hop.md
canonical_url: https://help.salesforce.com/s/articleView?id=xcloud.apexguru_antipattern_soql_in_loop_one_hop.htm&release=264.0.0&type=5
source_site: help.salesforce.com
content_type: documentation
content_hash: c937286be32b56f65f08f0816fc1f8143262ef06e228eb5693e95df5599d11c2
description: 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.
products:
  - Cross Cloud
release: "264"
---
# 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

```java
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
          }
      }
  }
```