Apex Bulkification: Fixing SOQL and DML in Loops
Apex bulkification means one query and one DML instead of hundreds. Learn to rewrite loops into map lookups, and find the 10,000-row ceiling that stops you.
TL;DR
Bulkification means your code does a fixed amount of work no matter how many
records it gets. One query outside the loop. One DML statement at the end. A
map to look things up. That pattern is the difference between code that runs in
milliseconds and code that throws System.LimitException the first time a real
user saves a record.
What Bulkification Actually Means
Here is the whole idea in one sentence: the number of queries and DML statements your code issues must not change when the number of records changes.
Most code that breaks this rule looks perfectly reasonable. You write a method that takes a list of records and does something to each one. It works for one record. It works for ten. The problem only shows up when the platform hands your code two hundred records at once.
I measured this on a scratch org (API version 68.0). Five accounts, two
contacts each. The loop version used five SOQL queries. The bulkified version
used one. The update at the end cost one DML statement in both cases.
| Approach | Records | SOQL queries | DML statements |
|---|---|---|---|
| Query inside the loop | 5 | 5 | 1 |
| One query, one map | 5 | 1 | 1 |
Five records is a toy. The platform processes up to 200 records in a single trigger call, so the loop version of a real trigger would use 200 queries and burn through the 100-query limit on the first save.
The Two Loops That Cause It
There are only two shapes of code that break bulkification, and you will write both of them.
SOQL inside a loop. You need something about each record, so you query for it right there, inside the loop.
DML inside a loop. You need to change each record, so you save it right there, inside the loop.
Both burn a governor limit that has a hard cap. 100 SOQL queries per transaction. 150 DML statements per transaction. A loop that runs 200 times hits both.
Here is the loop version. It compiles, it runs, and it returns the right answer for a single account:
public class CountContactsInLoop {
public static void describe(List<Account> accounts) {
for (Account account : accounts) {
List<Contact> contacts = [
SELECT Id, LastName
FROM Contact
WHERE AccountId = :account.Id
];
account.Description = 'Has ' + contacts.size() + ' contacts';
}
}
}The query is inside the loop. One account costs one query. Two hundred
accounts cost two hundred queries, and the transaction dies with
System.LimitException: Too many SOQL queries: 101.
One Query, One Map, One Update
The fix is a shape change, not a micro-optimization. You move the query above the loop, key the results by the field you will look them up with, and you save everything once at the end.
public class CountContactsBulkified {
public static void describe(List<Account> accounts) {
if (accounts == null || accounts.isEmpty()) {
return;
}
List<Contact> contacts = [
SELECT Id, AccountId
FROM Contact
WHERE AccountId IN :accounts
];
Map<Id, Integer> contactCounts = new Map<Id, Integer>();
for (Contact contact : contacts) {
if (!contactCounts.containsKey(contact.AccountId)) {
contactCounts.put(contact.AccountId, 0);
}
contactCounts.put(
contact.AccountId,
contactCounts.get(contact.AccountId) + 1
);
}
for (Account account : accounts) {
Integer count = contactCounts.get(account.Id);
account.Description = count == null
? 'Has no contacts'
: 'Has ' + count + ' contacts';
}
update accounts;
}
}Three changes did all the work:
- The query moved above the loop and now uses
INso it takes the whole list in one round trip. - A
Map<Id, Integer>keyed byAccountIdreplaced the per-record lookup. Getting a count is now a map read, not a query. - The
updatemoved below the loop, so it is one statement for every record.
The IN clause needs the list to be a real collection, not a single value.
That is why the query binds :accounts and not :account.Id.
Maps Beat Nested Loops
There is a second, sneakier version of the same bug. It has no query in it at all, so it slips past the limit checks and just runs slowly.
public class NestedLookupSlow {
public static void describe(List<Account> accounts) {
for (Account account : accounts) {
for (Contact contact : [
SELECT Id, LastName
FROM Contact
WHERE AccountId = :account.Id
]) {
account.Description = 'Contact: ' + contact.LastName;
}
}
}
}This runs one query per account, and the work inside the loop grows with the size of the inner list. It is quadratic: double the accounts and you do about four times the work.
The bulkified version does one query and one map, and the inner work becomes a map read:
public class NestedLookupFast {
public static void describe(List<Account> accounts) {
if (accounts == null || accounts.isEmpty()) {
return;
}
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact contact : [
SELECT Id, AccountId, LastName
FROM Contact
WHERE AccountId IN :accounts
]) {
if (!contactsByAccount.containsKey(contact.AccountId)) {
contactsByAccount.put(contact.AccountId, new List<Contact>());
}
contactsByAccount.get(contact.AccountId).add(contact);
}
for (Account account : accounts) {
List<Contact> found = contactsByAccount.get(account.Id);
account.Description = found == null
? 'No contacts'
: 'Contacts: ' + found.size();
}
update accounts;
}
}Same input, same output, one query instead of many. When you compare the two versions, look for the map. A map in the middle of a method is the sign of bulkified code.
One DML Statement for the Whole List
DML works the same way. Building a list and saving it once costs one statement, no matter how long the list is.
public class InsertContactsOnce {
public static void insertContacts(List<String> lastNames) {
List<Contact> contacts = new List<Contact>();
for (String lastName : lastNames) {
contacts.add(new Contact(LastName = lastName));
}
insert contacts;
}
}That insert touches every row for the price of one statement. The DML
statement limit is 150, so the difference between one statement and 150
statements is the difference between working and not working.
Partial Success: The Version That Keeps Going
Bulk DML fails as a unit by default. One bad row and the whole thing rolls
back. When you want the good rows to survive, use the Database methods with
allOrNone set to false, and read the result list.
List<Contact> newContacts = new List<Contact>{
new Contact(LastName = 'Good One'),
new Contact(LastName = 'Bad One', Email = 'not-an-email')
};
List<Database.SaveResult> results = Database.insert(newContacts, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
System.debug('Row ' + i + ' saved with Id ' + results[i].getId());
} else {
System.debug(
'Row ' + i + ' failed: ' +
results[i].getErrors()[0].getStatusCode() + ' - ' +
results[i].getErrors()[0].getMessage()
);
}
}I ran exactly this on a scratch org. The first row saved and came back with
an Id. The second row came back as INVALID_EMAIL_ADDRESS with the message
Email: invalid email address: not-an-email. The first row was not rolled
back. Note that Database.insert with a list returns
List<Database.SaveResult>, one entry per row, in the order you passed them.
The Ceiling Bulkification Cannot Cross
Here is the part people get wrong. The 10,000-row DML limit is per transaction, not per statement.
A transaction can insert 10,000 rows. I confirmed both ends of that on a
scratch org: an insert of exactly 10,000 contacts succeeded, and an insert of
10,001 failed with System.LimitException: Too many DML rows: 10001.
But splitting the work into chunks inside the same transaction does not help. Five chunks of 5,000 in one transaction still dies at the same ceiling, because the counter is cumulative:
List<Contact> all = new List<Contact>();
for (Integer i = 0; i < 25000; i++) {
all.add(new Contact(LastName = 'Chunk ' + i));
}
for (Integer start = 0; start < all.size(); start += 5000) {
List<Contact> chunk = new List<Contact>();
for (Integer i = start; i < start + 5000 && i < all.size(); i++) {
chunk.add(all[i]);
}
insert chunk;
}That code looks like the fix for more than 10,000 rows. It is not. It runs until the third chunk pushes the transaction over the limit, and then the whole transaction rolls back.
To go past 10,000 rows you need separate transactions, which means async
Apex. Batch Apex is the tool for this. Each execute call is its own
transaction with its own fresh governor budget:
public class DescribeAccountsBatch implements Database.Batchable<sObject> {
public Database.QueryLocator start(Database.BatchableContext context) {
return Database.getQueryLocator('SELECT Id, Name FROM Account');
}
public void execute(
Database.BatchableContext context,
List<Account> scope
) {
for (Account account : scope) {
account.Description = 'Described: ' + account.Name;
}
update scope;
}
public void finish(Database.BatchableContext context) {
System.debug('DescribeAccountsBatch finished');
}
}Run it with Database.executeBatch(new DescribeAccountsBatch()). Batch Apex
hands each execute a chunk of up to 200 records and gives that chunk a fresh
set of limits, so the 10,000-row ceiling applies per chunk instead of to the
whole job. If you want a bigger chunk, Database.executeBatch accepts a scope
value, up to 2,000 records when the batch starts from a QueryLocator.
Heap Is the Other Ceiling
The other wall you will hit is memory. Apex gives a transaction 10 MB of heap in sync code and 25 MB in async code.
Loading everything into a list is not free. On a scratch org, 10,000 Account objects with a name, phone, website, and description took about 1.7 MB of heap in the list, roughly 170 bytes per record. Ten thousand Contacts with names and emails took about 800 KB, roughly 80 bytes per record.
So the 10 MB heap buys you tens of thousands of records, not millions. And before heap gets there, SOQL stops you: a single transaction can retrieve 50,000 rows. Bulkify your code, and still plan for the work that is too big for one transaction.
Triggers Hand You 200 Records
One more piece of the puzzle. A trigger does not run once per record. The platform batches them, and a trigger call is handed up to 200 records at a time.
That number is the reason bulkification is not optional. Code that works for one record and is wrong for 200 is not slow. It is broken, and it will break in production on a bulk edit long before a user complains.
Prove It Instead of Guessing
Do not trust yourself to count queries by eye. The platform will tell you. Read the query counter before and after the work:
Integer before = Limits.getQueries();
// your bulkified work goes here
System.debug('Queries used: ' + (Limits.getQueries() - before));Limits.getQueries() is the number of SOQL queries the transaction has used.
Limits.getLimitQueries() is the cap, which is 100 in sync code. The same
pair exists for every limit: getDmlStatements, getDmlRows, getCpuTime,
getHeapSize.
One warning. There is no Limits.getLimitMap(). The
governor limits post covers the
full list of caps and how to read them. The way to read the whole set at once
is System.OrgLimits.getMap(), which returns a map of System.OrgLimit
objects, and it reports org-level limits rather than the per-transaction
counters on Limits.
Where To Practice Next
Start with the bulk insert contacts challenge, which is the one-statement pattern in its purest form, then do the bulk insert accounts challenge for the same idea on a different object. When you are ready to move past the one-transaction ceiling, the bulk update account industry challenge puts the pieces together. If you want the theory behind the patterns, the apex fundamentals path walks through them one at a time.
About Warren Walters
Salesforce MVP and transformative mentor with 8+ years in the Salesforce realm. Founder of Lightning Challenge, dedicated to nurturing the next generation of Salesforce talent through hands-on practice and real-world coding challenges.
Visit Profile →