Sub topic 6
Removing SOQL and DML from loops
This chapter assumes you know basic Apex syntax, SOQL, and DML statements, and that you know a trigger receives a list of records in Trigger.new. You should also know that one transaction shares a single set of governor limits, such as 100 SOQL queries and 150 DML statements for synchronous Apex.
Why loops are the problem
A trigger can receive up to 200 records in one invocation. Any SOQL query or DML statement inside a for loop runs once per record. With 101 records, a query inside the loop runs 101 times and the transaction fails with System.LimitException: Too many SOQL queries: 101. The code often passes with one record in manual testing and fails only on a data load.
The fix is always the same shape: collect, operate once, then use the result.
Spotting the anti-pattern
This trigger runs one query per contact. It also throws a QueryException when AccountId is null, because a single-record query that returns no rows fails.
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
// Anti-pattern: one SOQL query per record
Account a = [SELECT Id, Industry FROM Account WHERE Id = :c.AccountId];
if (a.Industry == 'Banking') {
c.Description = 'Banking contact';
}
}
}The three-step rewrite
- Collect. Loop over
Trigger.newand add the values you need to aSet. A Set removes duplicates, and you skip null values here. - Operate once. Run one query with an
INclause, or one DML statement on a wholeList. - Use the result. Loop again and read from a
Mapkeyed by ID. Map lookups cost no queries.
Here is the bulkified trigger:
trigger ContactTrigger on Contact (before insert, before update) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accountsById.get(c.AccountId);
if (a != null && a.Industry == 'Banking') {
c.Description = 'Banking contact';
}
}
}This uses one query for 1 record or for 200. The Map constructor accepts a query result and keys each record by its Id. When AccountId is null, get returns null, so the a != null check handles it.
The same idea for DML
Do not call insert, update, or delete inside the loop. Build a list, then run one statement after the loop. The handler below does this for follow-up tasks:
public with sharing class OpportunityTriggerHandler {
public static void createFollowUpTasks(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : newOpps) {
Boolean isWon = opp.StageName == 'Closed Won';
Boolean wasWon = oldMap != null
&& oldMap.get(opp.Id).StageName == 'Closed Won';
if (isWon && !wasWon) {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}The isEmpty() check avoids a DML statement when there is nothing to write. Even an empty DML call counts against the limit.
Hidden loops
Operations also hide behind method calls. If a helper method runs a query, calling it inside a loop has the same effect as writing the query there. Check every method called from a loop body. Also watch for nested loops, where a query in the inner loop runs once per outer and inner pass.
Exercise
A trigger loops over Trigger.new and calls update acct; for each related Account inside the loop. What are the three changes that make it bulkified?
Show answer
Create a List<Account> before the loop, add each modified account to the list inside the loop, and run a single update on the list after the loop, guarded by an isEmpty() check. Gather IDs in a Set first if the accounts must be queried.