Sub topic 2
Removing SOQL and DML from Loops
Assume you know basic Apex, sObjects, SOQL, and DML. This chapter focuses on making one trigger invocation handle many records safely.
Why loops cause failures
A trigger receives a list of records. Salesforce can process up to 200 records in one trigger invocation. All records share the transaction's governor limits, which restrict operations such as SOQL queries and DML statements.
This pattern runs one query for every contact:
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
Account a = [
SELECT Id, Industry
FROM Account
WHERE Id = :c.AccountId
];
if (a.Industry == 'Banking') {
c.Description = 'Banking contact';
}
}
}With 101 contacts, this code can exceed the synchronous limit of 100 SOQL queries. DML inside the loop has the same problem. It also makes partial processing and error handling harder.
Collect IDs with collections
A collection stores multiple values:
- A
Set<Id>stores unique IDs. - A
List<sObject>stores records in order and is useful for DML. - A
Map<Id, sObject>stores records by ID for fast lookup.
First collect related Account IDs. Skip null IDs because a contact does not always have an account.
Query once and use a Map
Use one SOQL query with an IN clause. The map then connects each contact to its account without another query.
trigger ContactTrigger on Contact (after insert) {
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]
);
List<Task> tasks = new List<Task>();
for (Contact c : Trigger.new) {
Account accountRecord = accountsById.get(c.AccountId);
if (accountRecord != null && accountRecord.Industry == 'Banking') {
tasks.add(new Task(
Subject = 'Review banking contact',
WhoId = c.Id,
OwnerId = c.OwnerId
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}The trigger performs one query and one DML statement, regardless of how many contacts meet the condition.
Exercise
What should replace a SOQL query inside a loop?
Show answer
Collect the needed IDs in a Set, query related records once with an IN clause, and retrieve each result from a Map.