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:

    1for (String name : names) {
    2   Account[] accs = [SELECT Name FROM Account WHERE Name =: name];

    Use:

    1for (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:

    1for (String n : names) {
    2   insert new Account(Name = n);

    Use:

    1Account[] accs = new List<Account>();
    2for (String n : names) {
    3   accs.add(new Account(Name = n));
    4}
    5insert accs;

Retired

As of August 2025, Salesforce Code Analyzer v4 is retired and no longer supported. Use Code Analyzer v5 instead.