Sub topic 12
Bulk-safe query patterns
This chapter assumes you can write inline SOQL, use bind variables, and know that Apex enforces governor limits per transaction. A synchronous transaction allows 100 SOQL queries. A trigger can receive up to 200 records at once, so a query inside a per-record loop fails as soon as the batch is large enough.
Why queries inside loops fail
Code that works when you save one record can break when a data load or integration saves many. The loop below runs one query per contact.
for (Contact c : contacts) {
Account a = [SELECT Name FROM Account WHERE Id = :c.AccountId];
}With 101 contacts, the 101st iteration throws System.LimitException: Too many SOQL queries: 101. Tests that insert a single record will not reveal this.
The pattern: collect, query once, look up
Bulk-safe code has three steps:
- Loop over the records and collect the Ids you need into a
Set<Id>. - Run one query with
WHERE Id IN :ids. - Put the results in a
Map<Id, SObject>and look up each record in the map.
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
for (Contact c : contacts) {
Account a = accountsById.get(c.AccountId);
if (a != null) {
System.debug(c.LastName + ' -> ' + a.Name);
}
}The Map<Id, Account> constructor accepts a list of records and uses each record's Id as the key. Two things in this code matter:
- The null check keeps
nullout of the Set, so the query does not receive a meaningless value. - The
a != nullcheck handles contacts whose account was not returned, for example because the user cannot see it.
The query count is now one, whether contacts holds 1 record or 200.
Letting the database do the join
Sometimes you do not need a second pass at all. A relationship query fetches parent fields in the same query, which uses no extra query.
List<Contact> contacts = [
SELECT Id, LastName, Account.Name
FROM Contact
WHERE AccountId IN :accountIds
];Prefer this when you are already querying the child records. Use the Set and Map pattern when the records come from somewhere else, such as Trigger.new.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Query inside a `for` loop | `Too many SOQL queries: 101` | Collect Ids, query once |
| Passing a list of records to `IN` | Type error | Collect the Ids into a `Set<Id>` first |
| Not checking the map result | `NullPointerException` | Test `get()` for `null` |
| Calling a method that queries from inside a loop | Same limit error, harder to see | Make the method accept a collection |
Verify with a bulk test
Test with more than one record. Inserting 200 records exercises the same code path a bulk load would.
@isTest
private class BulkQueryTest {
@isTest
static void handlesTwoHundredContacts() {
Account acct = new Account(Name = 'Bulk Parent');
insert acct;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'C' + i, AccountId = acct.Id));
}
insert contacts;
Test.startTest();
Set<Id> ids = new Set<Id>();
for (Contact c : contacts) {
ids.add(c.AccountId);
}
Map<Id, Account> byId = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :ids]
);
Integer queriesUsed = Limits.getQueries();
Test.stopTest();
Assert.areEqual(1, byId.size());
Assert.areEqual(1, queriesUsed);
}
}Exercise
A trigger handler loops over 150 new Opportunity records and runs one SOQL query per record to get the Account. Why does this fail, and how do you fix it?
Show answer
Each iteration uses one of the 100 allowed queries in the transaction, so the 101st throws a LimitException. Collect the AccountId values into a Set<Id>, run one query with WHERE Id IN :accountIds into a Map<Id, Account>, and look up each Opportunity's account in the map.