Sub topic 5
Moving SOQL out of loops
This chapter assumes you can read basic Apex and SOQL, know List, Set and Map, and know what a trigger and its before and after events are. Earlier chapters covered why governor limits exist and why triggers receive up to 200 records at a time. Here you will apply that knowledge to the most common cause of limit failures: a query inside a loop.
Why a query in a loop fails
A synchronous Apex transaction can issue at most 100 SOQL queries. An asynchronous transaction (Queueable, Batch, future) gets 200. The limit counts every query statement that runs, not the number of rows returned. A query that returns one row costs the same as a query that returns 10,000 rows.
A loop that runs a query on each iteration therefore uses one query per record. This code works when you test it by saving one record in the UI. It fails when a data load or an integration sends a batch.
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;
}
}With 101 contacts in one batch, the 101st iteration throws System.LimitException: Too many SOQL queries: 101. The exception cannot be caught, and the whole transaction rolls back, including the 100 contacts that processed fine.
The same code has a second bug. If c.AccountId is null, the query returns no rows and the assignment throws a QueryException. Bulkifying the code gives you a chance to fix both problems.
The three-step pattern
Every fix follows the same shape:
- Collect. Loop once over the input records and gather the keys you need into a
Set. - Query. Run one query outside any loop, using
WHERE field IN :set. - Look up. Loop again over the input records and read results from a
Map.
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;
}
}
}This uses one query whether the batch holds 1 contact or 200. The diagram shows the difference in control flow.
Why a Map and not a List
The Map<Id, Account> constructor accepts a List<Account> and keys each record by its Id. This is the shortest way to get constant-time lookup by Id. If you returned a List instead, you would need a nested loop to find the right account for each contact. That nested loop uses no queries, but it costs CPU time, which you will meet in a later chapter.
Details that cause bugs
Empty and null keys
WHERE Id IN :accountIds with an empty set is legal and returns no rows. It still counts as one query. If the empty case is common, skip the query:
Map<Id, Account> accounts = new Map<Id, Account>();
if (!accountIds.isEmpty()) {
accounts = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
}Filter nulls before adding to the set. A null in the set is harmless to the query but means you were probably about to look up a record that cannot exist.
Map.get returns null for a missing key
accounts.get(someId) returns null if the key is absent. Dereferencing it without a check throws a NullPointerException. A key can be missing because the field was null, because the record was deleted, or because the running user cannot see it. Check for null after every get, as the example above does.
Relationship fields are not populated on Trigger.new
In a trigger, c.Account.Industry is null even when AccountId is set. Trigger records contain only the fields that were saved, not the related records. You must query for the parent, which is why the pattern above is needed. Trigger.newMap and Trigger.oldMap help in another way: in update and after triggers they let you look up the old or new version of the same record by Id without a query.
Matching on a field other than Id
You can key a Map by any field. Use a Map<String, Account> when you match on a unique text value such as an external Id. If the field is not unique, a plain Map keeps only the last record for each key. Lowercase text keys on both sides if the match should ignore case, because Map keys of type String are case-sensitive.
One parent, many children
The previous example maps one parent to each record. Often you need the opposite: all children for each parent. Use a Map<Id, List<SObject>> and build it with a loop over a single query result.
public class ContactLookup {
public static Map<Id, List<Contact>> byAccount(Set<Id> accountIds) {
Map<Id, List<Contact>> result = new Map<Id, List<Contact>>();
if (accountIds == null || accountIds.isEmpty()) {
return result;
}
for (Contact c : [
SELECT Id, LastName, Email, AccountId
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 over the bracketed query is a SOQL for loop. It is still one query. The records are returned from the platform in chunks of 200, which keeps heap use lower than assigning the full result to a List first. The query statement itself counts once, as normal.
A caller then reads byAccount(ids).get(accountId). Handle the case where this returns null, which means the account has no contacts.
Alternative: a subquery
If you already need to query the parents, a child subquery fetches both levels in one statement.
Set<Id> accountIds = new Map<Id, Account>(
[SELECT Id FROM Account WHERE Industry = 'Energy']
).keySet();
for (Account a : [
SELECT Id, Name, (SELECT Id, LastName FROM Contacts)
FROM Account
WHERE Id IN :accountIds
]) {
System.debug(a.Name + ' has ' + a.Contacts.size() + ' contacts');
}Subqueries count as one query. They return child rows that count toward the 50,000-row total for the transaction. Use them when you need the parent fields and the children together. Use the separate child query when you only have parent Ids and no need for parent fields.
Aggregates instead of fetching rows
If you only need a count or a sum per parent, ask the database to compute it. This returns one row per parent instead of every child row, which saves rows, heap and CPU.
public class OpenOpportunityCounts {
public static Map<Id, Integer> forAccounts(Set<Id> accountIds) {
Map<Id, Integer> counts = new Map<Id, Integer>();
if (accountIds == null || accountIds.isEmpty()) {
return counts;
}
for (AggregateResult ar : [
SELECT AccountId acctId, COUNT(Id) total
FROM Opportunity
WHERE AccountId IN :accountIds AND IsClosed = false
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acctId'), (Integer) ar.get('total'));
}
return counts;
}
}Accounts with no open opportunities do not appear in the result. Treat a missing key as zero: counts.containsKey(id) ? counts.get(id) : 0.
Hidden queries in helper methods
The loop does not have to contain the square brackets. A query hidden inside a method called from a loop has the same effect.
public class IndustryHelper {
// Looks harmless, but each call costs one query.
public static String industryFor(Id accountId) {
return [SELECT Industry FROM Account WHERE Id = :accountId].Industry;
}
}
// Caller:
// for (Contact c : Trigger.new) {
// c.Description = IndustryHelper.industryFor(c.AccountId);
// }Fix this by changing the helper's signature to accept a collection and return a Map:
public class IndustryHelper {
public static Map<Id, String> industriesFor(Set<Id> accountIds) {
Map<Id, String> result = new Map<Id, String>();
if (accountIds == null || accountIds.isEmpty()) {
return result;
}
for (Account a : [
SELECT Id, Industry FROM Account WHERE Id IN :accountIds
]) {
result.put(a.Id, a.Industry);
}
return result;
}
}> Rule of thumb: a method that takes a single Id or a single record and runs SOQL or DML should make you suspicious. Name bulk methods with plural parameters, such as Set<Id> or List<Contact>, so the intent is visible at the call site.
Loops are not the only hiding place. Other places where per-record queries appear include:
- Methods called from
forloops,whileloops, andforEach-style iteration over a collection. - Property getters that run a query each time they are read.
- Recursive calls, where each level runs a query.
- Code reached from a trigger, which runs once per batch but may be invoked many times in one transaction.
The limit is shared across the whole transaction
Triggers, flows, process automation and other triggers on related objects all run inside the same transaction and draw from the same 100-query budget. Your trigger may use only 2 queries. If a bulk insert also fires a second trigger on the same object, a flow that does lookups, and cascading updates on child objects, the total can still pass 100. Each bulkified piece keeps the count independent of batch size, but the fixed costs still add up. Use the Limits class from a later chapter to see where the budget goes.
A short checklist for review
When reviewing Apex for query-in-loop problems, check these in order:
- Are there square-bracket queries or
Database.querycalls inside any loop body? - Does any method called from a loop run SOQL?
- Does each query use
IN :setrather than= :singleValuewhere it handles trigger records? - Is every
Map.getresult checked fornull? - Is the query skipped when the key set is empty?
- Could an aggregate query replace fetching child rows?
Exercise
A trigger on Opportunity (before update) loops over Trigger.new. Inside the loop it runs [SELECT Name FROM Account WHERE Id = :opp.AccountId] and copies the name into a custom field. Describe how you would bulkify it, and name two checks the new code needs.
Show answer
Loop once over Trigger.new and add each non-null AccountId to a Set<Id>. Run one query, SELECT Id, Name FROM Account WHERE Id IN :accountIds, and store the result in a Map<Id, Account> (skip the query if the set is empty). Loop again over Trigger.new, call accounts.get(opp.AccountId), and copy the name. The two checks are: filter out null AccountId values before adding to the set, and test the Map.get result for null before reading Name, because a missing account would otherwise cause a NullPointerException.
Exercise
A trigger has a helper call Util.getOwnerEmail(c.OwnerId) inside a loop, and the helper contains a SOQL query. The trigger has no query statements of its own. Why can it still hit the 100-query limit, and what change fixes it?
Show answer
Each call to the helper runs one query, so a batch of 101 or more records makes 101 or more queries even though the trigger has no brackets. Change the helper to take a Set<Id> of owner Ids and return a Map<Id, String> built from one query with WHERE Id IN :ownerIds. Call it once before the loop and read the Map inside the loop.