Sub topic 5
Moving SOQL Out of Loops
This chapter assumes you know basic Apex syntax, the List, Set and Map collections, simple SOQL, and how before and after trigger events work. It also assumes you know that a trigger receives up to 200 records per batch.
Why a query in a loop fails
Apex allows 100 synchronous SOQL queries per transaction. A trigger fires once per batch of up to 200 records, not once per record. If the trigger runs one query for every record, a batch of 101 records or more uses 101 queries or more. The transaction then fails with System.LimitException: Too many SOQL queries: 101.
This code often passes manual testing, because you usually save one record at a time. It breaks later during a data load, an integration, or a Flow that creates many records at once.
trigger ContactBefore on Contact (before insert) {
for (Contact c : Trigger.new) {
// Anti-pattern: one query per record
Account a = [SELECT Id, Industry FROM Account WHERE Id = :c.AccountId];
c.Description = 'Industry: ' + a.Industry;
}
}There is a second bug. If c.AccountId is null, the query returns no rows and a assignment throws a QueryException. Bulkified code has to handle missing parents.
The three-step pattern
Almost every fix for a query in a loop follows the same shape:
- Collect. Loop once over the trigger records and put the lookup keys in a
Set. - Query. Run one SOQL query with
WHERE Id IN :set, and store the results in aMap. - Use. Loop again and read each related record from the map by key.
A Set removes duplicate keys for you. A Map<Id, SObject> gives you a lookup without another query or a nested loop.
The bulkified version
trigger ContactBefore on Contact (before insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accounts.get(c.AccountId);
if (a != null) {
c.Description = 'Industry: ' + a.Industry;
}
}
}Points to notice:
- The query runs once, whether the batch has 1 record or 200.
- The
Mapconstructor accepts a list of SObjects and keys the map byId. You don't need a loop to fill it. - The null check on
AccountIdkeeps null values out of the set. The null check onahandles Ids that matched no row. - Two loops are fine. Loops cost CPU time, which is far cheaper than queries.
Other places a query hides
A query does not have to sit directly inside a for loop to count as one. Watch for these:
- A method that contains a query, called from inside a loop. The loop looks clean, but each call still runs a query.
- A query inside a
whileloop or inside aforloop's body in a helper class. - A trigger that calls a handler once per record instead of passing the whole list.
The fix for a helper method is to change its signature. Pass a Set<Id> or List<SObject> in, and return a Map. The caller then makes one call for the whole batch.
Querying by something other than Id
Sometimes the key is not an Id. For example, you might match Contacts to Accounts by name. Use a Set<String> for the keys and build the map yourself:
Map<String, Account> byName = new Map<String, Account>();
for (Account a : [SELECT Id, Name FROM Account WHERE Name IN :names]) {
byName.put(a.Name, a);
}Looping directly over a SOQL query, as above, is allowed. The query runs once, and Apex retrieves the rows in chunks of 200 internally.
Related records can also be fetched in one query with a subquery, such as SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :ids. This returns each parent with its children attached, so you need no second query.
Common mistakes
| Mistake | Result |
|---|---|
| Querying inside the loop | `Too many SOQL queries: 101` on batches over 100 |
| Skipping the null check on the key | Null in the `IN` set, or `null` returned from `get` |
| Using `[SELECT ... LIMIT 1]` assigned to one object | `QueryException` when no row matches |
| Testing only with one record | The bug stays hidden until a bulk load |
Exercise
A trigger on Opportunity (before insert) runs [SELECT Name FROM Account WHERE Id = :o.AccountId] inside for (Opportunity o : Trigger.new). Describe, in three steps, how to rewrite it so it uses one query for any batch size. Which collection types do you use, and why?
Show answer
First, loop over Trigger.new and add each non-null o.AccountId to a Set<Id>, which removes duplicates. Second, run one query, SELECT Id, Name FROM Account WHERE Id IN :accountIds, and load the result into a Map<Id, Account>. Third, loop over Trigger.new again and use accounts.get(o.AccountId), checking that the result is not null before using it. The Set holds unique keys for the IN clause, and the Map gives constant-time lookup without extra queries.