Sub topic 6
Removing SOQL and DML from loops
This chapter assumes you can read basic Apex, know that triggers receive Trigger.new as a list, and have written simple SOQL queries and DML statements. The previous chapters covered governor limits and why triggers always receive a list. This chapter turns that knowledge into a repeatable refactoring.
Why a statement in a loop breaks
A trigger can receive up to 200 records per invocation. A loop over Trigger.new therefore runs up to 200 times. Any SOQL query or DML statement in the loop body runs once per iteration.
The limits for a synchronous transaction are:
| Resource | Limit |
|---|---|
| SOQL queries issued | 100 |
| DML statements issued | 150 |
| Rows retrieved by SOQL | 50,000 |
| Rows processed by DML | 10,000 |
A trigger with one query in its loop passes with 5 records and fails with 101. The failure is a System.LimitException, and it cannot be caught. The whole transaction rolls back. This is why such triggers often pass manual testing, where you save one record at a time, and then fail during a data load.
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';
}
}
}This trigger has a second defect. If c.AccountId is null, the query returns no rows and the assignment to a single Account throws a QueryException. A bulk-safe version must handle null IDs explicitly.
The refactoring recipe
Every fix follows the same five steps, whatever the object or query.
- Loop once to collect the keys you need (IDs or other values) into a
Set. - Run a single query that filters with
IN :theSet. - Put the results into a
Mapso you can look them up by key. - Loop again over the trigger records. Read from the Map and decide what to change.
- Gather the records to write into a collection, then run one DML statement after the loop.
Apply the recipe to the contact 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';
}
}
}Three details matter here:
- The
Setremoves duplicates. 200 contacts on 3 accounts produce a set of 3 IDs. new Map<Id, Account>(queryResult)builds a map keyed by record ID in one expression.accountsById.get(null)returnsnulland does not throw, so the second loop needs only a null check on the result.
The query still runs when accountIds is empty. It returns no rows but counts toward the 100-query limit. In a trigger this cost is small, but in shared code you can add if (accountIds.isEmpty()) return; to skip it.
Removing DML from loops
DML follows the same logic. A DML statement in a loop consumes one of the 150 statements on every iteration, so a batch of 151 records fails.
Here is an after insert trigger on Opportunity that updates the parent account once per record:
trigger OpportunityAccountFlag on Opportunity (after insert) {
for (Opportunity opp : Trigger.new) {
if (opp.AccountId != null) {
// Anti-pattern: one DML statement per record
update new Account(
Id = opp.AccountId,
Description = 'Has opportunities'
);
}
}
}The fix collects the changes and writes them once. Use a Map and not a List for the records to update:
trigger OpportunityAccountFlag on Opportunity (after insert) {
Map<Id, Account> accountsToUpdate = new Map<Id, Account>();
for (Opportunity opp : Trigger.new) {
if (opp.AccountId != null) {
accountsToUpdate.put(
opp.AccountId,
new Account(
Id = opp.AccountId,
Description = 'Has opportunities'
)
);
}
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate.values();
}
}If 50 opportunities share one account, a List<Account> would contain that account 50 times. Salesforce rejects a DML list with the same ID twice and throws a System.ListException ("Duplicate id in list"). A Map keyed by ID keeps one entry per account and makes the collision impossible.
Hidden loops
Not every offender sits visibly inside a for block. A query or DML statement inside a method has the same cost if the method is called once per record.
public with sharing class AccountLookup {
// Looks harmless, but costs one query per call
public static Account getAccount(Id accountId) {
return [SELECT Id, Industry FROM Account WHERE Id = :accountId];
}
}
// In the trigger: one query per iteration, same defect as before
for (Contact c : Trigger.new) {
Account a = AccountLookup.getAccount(c.AccountId);
}The same applies to code reached through other routes:
- Utility methods that accept a single ID or record.
- Constructors that query.
- Nested loops, where the inner statement runs outer times inner times.
- Other triggers or flows fired by your DML, which share the same transaction limits.
The fix is to change the method signature so that it accepts and returns collections, for example Map<Id, Account> getAccounts(Set<Id> ids). A method that takes a single record is a warning sign in trigger code.
Grouping child records
Sometimes the lookup is one-to-many. To find the contacts of each account, query the children once and group them by parent ID in a Map<Id, List<Contact>>.
public with sharing class ContactGrouper {
public static Map<Id, List<Contact>> byAccount(Set<Id> accountIds) {
Map<Id, List<Contact>> result = new Map<Id, List<Contact>>();
for (Contact c : [
SELECT Id, AccountId, Email
FROM Contact
WHERE AccountId IN :accountIds
]) {
if (!result.containsKey(c.AccountId)) {
result.put(c.AccountId, new List<Contact>());
}
result.get(c.AccountId).add(c);
}
return result;
}
}The for loop here iterates over query results. It does not issue a query per pass, so it is safe. The query ran once, when the loop began.
Edge cases to check
- Row limits still apply. One query removes the query-count problem, but 200 records with many children each can exceed 50,000 rows. Filter the query to the fields and rows you need.
- Large
INlists. ASetof IDs from 200 records is well within the query size limits. Sets built from other sources may not be. - Query results do not include changes made earlier in the same loop. If your code updates a record and a later step needs the new value, read it from your in-memory collection and not from a second query.
- Null keys. Skip null IDs when collecting, and null-check lookups when reading.
Review checklist
Before you finish a trigger, scan it for these signs:
- Square-bracket SOQL,
Database.query, or a call to a query method inside anyfororwhileloop. insert,update,delete,upsert, orDatabase.*calls inside a loop.- Helper methods that take a single ID or record and run a statement.
- A
Listof records to update that could contain the same ID twice.
Exercise
A trigger on Case runs Contact c = [SELECT Id, Email FROM Contact WHERE Id = :cs.ContactId]; inside for (Case cs : Trigger.new). Describe the five-step fix, and name one extra check the new code needs.
Show answer
Collect each non-null cs.ContactId into a Set<Id>. Run one query with WHERE Id IN :contactIds. Store the results in a Map<Id, Contact> by passing the query to the Map constructor. Loop over Trigger.new and call contactsById.get(cs.ContactId). Gather any records to write into a collection and run one DML statement after the loop. The extra check is a null test on the value returned by get, because a case can have no contact or the contact may not be visible to the user.
Exercise
Why is a Map<Id, Account> safer than a List<Account> for collecting accounts to update from Trigger.new on Opportunity?
Show answer
Several opportunities can share one account. A list would then hold the same account ID more than once, and DML on that list throws a "Duplicate id in list" error. A Map keyed by ID keeps one entry per account.