Sub topic 12
Bulk-safe query patterns
This chapter assumes you can write inline SOQL, use bind variables, and read the governor limits from the previous chapters. It covers how to structure Apex so that one query serves many records, whether your code runs for 1 record or 200.
Why bulk safety matters
Apex code in a trigger does not run for one record at a time. A data load, an API call, or a batch can hand your code up to 200 records in a single transaction. A transaction that runs more than 100 synchronous SOQL queries fails with a System.LimitException: Too many SOQL queries: 101. This exception cannot be caught, and it rolls back the whole transaction.
Code with a query inside a loop works in a test with one record and then fails in production with 101 records. The fix is a pattern: collect the keys first, query once, and look results up in memory.
The three-step pattern
Bulk-safe code almost always follows the same three steps.
- Loop over the input records and collect the keys you need into a
Set. - Run one query with
WHERE ... IN :set. - Put the results in a
Mapand loop over the input again, reading from the map.
// Anti-pattern: one query per record
// for (Contact c : contacts) {
// Account a = [SELECT Name FROM Account WHERE Id = :c.AccountId];
// }
// Bulk-safe: collect Ids, query once, look up in a 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);
}
}Each step does a specific job:
- A
Setremoves duplicates. If 200 contacts share 3 accounts, the query filters on 3 Ids. - The null check keeps
nullout of the set. Anullin the set is legal, but it adds nothing useful and often hides a data problem. - The
Map<Id, Account>constructor accepts a list of sObjects and keys each record by itsId. You get this conversion without writing a loop. accountsById.get(...)returnsnullfor a missing key. It does not throw, so the second loop checks fornull.
The query count here is 1 regardless of input size. That is the property to aim for: the number of queries should depend on the code's structure, never on the data volume.
Binding collections
A bind variable can hold a collection when you use IN. The collection can be a Set, a List, or an Array of a compatible type.
Set<String> industries = new Set<String>{ 'Technology', 'Energy' };
List<Account> accts = [
SELECT Id, Name, Industry
FROM Account
WHERE Industry IN :industries
];Two details matter here:
- An empty collection is valid.
WHERE Id IN :emptySetreturns zero rows and still counts as one query. You do not need to skip the query to be correct, but skipping it saves a query when you know the set is empty. - Large collections have limits. The SOQL statement is limited in length, but bind variables are not counted as text in the query, so binding a collection avoids the length problem that string concatenation would cause.
Grouping children by parent
A query for child records often needs to be split back out per parent. Build a Map<Id, List<SObject>>.
Set<Id> accountIds = new Map<Id, Account>(
[SELECT Id FROM Account WHERE Industry = 'Technology']
).keySet();
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : [
SELECT Id, LastName, AccountId
FROM Contact
WHERE AccountId IN :accountIds
]) {
if (!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}
for (Id accId : contactsByAccount.keySet()) {
System.debug(accId + ' has ' + contactsByAccount.get(accId).size() + ' contacts');
}The new Map<Id, Account>(query).keySet() idiom is a short way to get a set of Ids from a query without a loop.
You can also use a parent-to-child subquery, which returns the grouping already done. Choose by what you need:
| Approach | Queries used | Use when |
|---|---|---|
| Separate query on the child with `IN :ids` | 1 | You already have the parent Ids, or you need to filter or sort children independently |
| Subquery on the parent | 1 | You need the parents and their children together |
| Query inside a loop | 1 per record | Never in bulk code |
A subquery still counts as one query, but its child rows count toward the total rows retrieved limit, and each subquery has its own row cap in some contexts. Test with realistic volumes.
Keeping other limits in view
SOQL queries are not the only limit. A bulk-safe query can still fail on a different limit.
| Limit (synchronous) | Value | What triggers it |
|---|---|---|
| SOQL queries per transaction | 100 | Queries in loops |
| Records retrieved by SOQL | 50,000 | A broad `WHERE` clause or no filter |
| Heap size | 6 MB | Storing very large lists or maps |
Asynchronous Apex such as Batch and Queueable has a larger heap (12 MB) and a 200 query limit. The 50,000 row limit still applies per transaction, except that a Batch Apex start method using a query locator can retrieve up to 50 million rows.
Two habits keep you inside these limits:
- Select only the fields you use. Extra fields increase heap use.
- Filter in the query instead of in Apex. Do not retrieve every account and then skip most in a loop.
Checking limits while you develop
The Limits class reports how much of each limit you have used. This helps you confirm a method is bulk-safe.
Integer before = Limits.getQueries();
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 200]
);
Integer used = Limits.getQueries() - before;
System.debug('Queries used: ' + used + ' of ' + Limits.getLimitQueries());
System.debug('Rows retrieved: ' + Limits.getQueryRows() + ' of ' + Limits.getLimitQueryRows());In a test, call the method with 200 records and assert that the query count is small and fixed.
Common mistakes
- Hidden queries in helper methods. A loop that calls a method, which in turn runs a query, is the same anti-pattern. Pass collections into helper methods, not single records.
- Querying in a constructor or getter. These run repeatedly. Cache the result in a variable.
- Querying for the record you already have. In a trigger,
Trigger.newalready holds the field values of the changed records. Query only for fields or related records you do not have. - Assuming one result. A map keyed by a non-unique field loses records, because a later
putreplaces an earlier one. Use aMap<Id, List<...>>when keys repeat. - Forgetting the
nullcheck after aMap.get.
Exercise
A trigger on Contact runs this code for each contact in Trigger.new: Account a = [SELECT Name FROM Account WHERE Id = :c.AccountId];. It passes with 5 test contacts and fails with 150 in a data load. Name the error, then rewrite the code so it uses a single query.
Show answer
The error is System.LimitException: Too many SOQL queries: 101, because the query runs once per contact and the limit is 100 per synchronous transaction. The fix is to collect the AccountId values into a Set<Id> (skipping nulls), run one query SELECT Id, Name FROM Account WHERE Id IN :accountIds into a Map<Id, Account>, and then loop over the contacts and read each account with accountsById.get(c.AccountId), checking for null.
Exercise
Why does a Map<String, Contact> keyed by Contact.LastName risk losing data when you fill it from a query, and what structure avoids that?
Show answer
Two contacts can share a last name, and Map.put replaces the existing value for a repeated key, so one contact is silently dropped. Use a Map<String, List<Contact>> so each key holds all matching contacts.