AvoidDatabaseOperationInLoop (Generally Available)

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.


@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.


Any database operation.

Match any violation message that you receive with this case to understand more about the violation.

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.

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:


  • 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: