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.
- Source
@AuraEnabled
-annotated methods.@InvocableMethod
-annotated methods.
@NamespaceAccessible
-annotated methods.@RemoteAction
-annotated methods. Any method returning aPageReference
object.public
-scoped methods on Visualforce Controllers.global
-scoped methods on any class.Messaging.InboundEmailResult handleInboundEmail()
methods on implementations ofMessaging.InboundEmailHandler
. Any method targeted during invocation.- Sink
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:
Use:
-
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:
Use: