---
schema_version: "1"
id: e3084126581d73af45356b438f09916cd031ba96d9c4e360673e29bc2e1f4ef0
title: AvoidDatabaseOperationInLoop (Retired)
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/code-analyzer/salesforce-code-analyzer/guides/v3x/salesforce-graph-engine/avoiddatabaseoperationinloop-rule.md
canonical_url: https://developer.salesforce.com/docs/platform/salesforce-code-analyzer/guide/avoiddatabaseoperationinloop-rule.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 4bc82022db16e9fcd5500fb9c28e4a44c9aae8d518c958fe58832de68040762e
products:
  - Salesforce Code Analyzer
---
# AvoidDatabaseOperationInLoop (Retired)

AvoidDatabaseOperationInLoop detects database operations that occur inside loops and that cause performance degradation. Database operations within loops cause performance degradations and exceed Salesforce governor limits.

## Definition

- Source

  - : `@AuraEnabled`-annotated methods.
    `@InvocableMethod`-annotated methods.  
     `@NamespaceAccessible`-annotated methods.
    `@RemoteAction`-annotated methods.
    Any method returning a `PageReference` object.
    `public`-scoped methods on Visualforce Controllers.
    `global`-scoped methods on any class.
    `Messaging.InboundEmailResult handleInboundEmail()` methods on implementations of `Messaging.InboundEmailHandler`.
    Any method targeted during invocation.

- Sink

  - : Any database operation.

## Interpreting Results

Match any violation message that you receive with this case to understand more about the violation.

### Loop Case

> A database operation occurred inside a loop.` [%s at %s:%d]`

Your code executes a database operation inside a loop statement. To move the database operation outside the loop, modify and then rescan your code.

## Best Practices

To remediate database operation violations, move these operations outside of loops. Follow these best practices.

- Instead of querying objects within a loop, use a SOQL `for` loop to iterate over a query’s results.

  For example, instead of:

  ```
  for (String name : names) {
     Account[] accs = [SELECT Name FROM Account WHERE Name =: name];
  ```

  Use:

  ```
  for (Account[] accs : [SELECT Name FROM Account WHERE Name IN :names]) {
  ```

- Instead of putting database operations within a loop, use the loop to iteratively construct lists of objects, and then perform the database operation on the full list after the loop.

  For example, instead of:

  ```
  for (String n : names) {
     insert new Account(Name = n);
  ```

  Use:

  ```
  Account[] accs = new List<Account>();
  for (String n : names) {
     accs.add(new Account(Name = n));
  }
  insert accs;
  ```
