A trigger passes its unit test with one record, then fails a 200-row import with System.LimitException: Too many SOQL queries: 101. Salesforce bulk data loads trigger this whenever Data Loader, Bulk API, or a scheduled integration pushes many records through code written for single-record edits. It usually surfaces in production first, because sandbox test data rarely reaches 200 rows per batch. The fix is not a retry or a bigger license. It is a change in how the trigger reads and writes data. Below, we refactor a per-record Opportunity trigger into a bulk-safe one and cover the trade-offs of each design choice.
Context and Setup
A governor limit is a per-transaction cap that the Apex runtime enforces on shared servers. Our scenario is an after update trigger on Opportunity that rolls the Amount of newly closed-won deals into a custom Total_Won__c field on the parent Account.
Prerequisites: a sandbox or scratch org, a Currency field named Total_Won__c on Account, and basic Apex knowledge.
The numbers explain the failure. The Apex Developer Guide sets synchronous transactions at 100 SOQL queries. It also allows 150 DML statements and 10,000 records processed by DML. Bulk loads deliver up to 200 records per trigger invocation, so one query per record fails on record 101.
Bulkifying Salesforce Apex Triggers in Three Steps
The short answer: collect IDs in the loop, query once, and write once.
Step 1: Find Where Salesforce Runs Queries Inside Loops
Locate every SOQL and DML statement that sits inside a loop over Trigger.new. Follow this audit:
Search the trigger and its helper classes for [SELECT and update inside loops.
List the fields the loop actually needs.
Note any condition that can skip records early.
This is the failing version:
apex
trigger OpportunityTrigger on Opportunity (after update) {
for (Opportunity opp : Trigger.new) {
// Why this fails: one query per record, so record 101 breaks the 100 SOQL limit
Account acc = [SELECT Id, Total_Won_c FROM Account WHERE Id = :opp.AccountId];
acc.Total_Wonc = (acc.Total_Wonc == null ? 0 : acc.Total_Won_c) + opp.Amount;
update acc; // Why this fails too: one DML per record, capped at 150 statements
}
}
Step 2: Collect, Query Once, Write Once
Gather the data into a Map, run one query with IN, then issue one DML statement. The map also merges several deals for the same Account.
apex
trigger OpportunityTrigger on Opportunity (after update) {
Map wonByAccount = new Map();
for (Opportunity opp : Trigger.new) {
// Why: act only on the stage change, so later edits do not double count
if (opp.StageName == 'Closed Won'
&& Trigger.oldMap.get(opp.Id).StageName != 'Closed Won'
&& opp.AccountId != null && opp.Amount != null) {
Decimal running = wonByAccount.containsKey(opp.AccountId)
? wonByAccount.get(opp.AccountId) : 0;
wonByAccount.put(opp.AccountId, running + opp.Amount);
}
}
if (wonByAccount.isEmpty()) return; // Why: skip the query when nothing qualifies
// One query for every parent Account in this chunk
List<Account> accounts = [SELECT Id, Total_Won__c FROM Account
WHERE Id IN :wonByAccount.keySet()];
for (Account acc : accounts) {
acc.Total_Won__c = (acc.Total_Won__c == null ? 0 : acc.Total_Won__c)
+ wonByAccount.get(acc.Id);
}
update accounts; // One DML statement for the whole list
}
Then test with 200 records in a single update call, because that is the real chunk size from Data Loader.
Step 3: Weigh the Trade-Offs
Bulkification fixes query counts, but it does not remove every limit. Compare these options:
Trigger with a handler class. Best for testability and bulk control. The cost is more files to maintain.
Record-triggered Flow. Faster to build for simple logic. Flows face similar per-transaction caps, so loops that query still fail.
Queueable Apex for heavy follow-up work. Asynchronous transactions allow 200 SOQL queries and 60,000 ms of CPU. The cost is eventual consistency, so the Account total updates a moment later.
Real-World Application
In one of our Salesforce projects at Oodles, a Realestate client loaded 1000 plus records nightly from website through Bulk API 2.0. An Opportunity trigger hit the 101 SOQL error on 10 percent of runs. We applied the map pattern above, moved it into a Queueable job, and added a 200-record test to the deployment pipeline.
Key Takeaways
Treat 200 records as normal trigger input, and write every trigger and test for that size.
Aim for one SOQL query and one DML statement per trigger context; a per-record query is a defect.
Maps keyed by record ID remove queries and merge duplicate parents safely.
Flows share per-transaction limits, so moving logic out of Apex does not cure a query-in-loop design.
Push heavy follow-up work to Queueable Apex when the business accepts slightly delayed results.
Hit a different governor limit? Share the error in the comments, or send your Salesforce architecture questions to our team.
What is a governor limit in Salesforce?
A governor limit is a per-transaction cap that Salesforce enforces because customers share servers. Synchronous Apex allows 100 SOQL queries, 150 DML statements, and 10,000 ms of CPU time. Exceeding one throws an exception that code cannot handle.
How many records does a trigger process at once?
Triggers receive up to 200 records per invocation. Data Loader batches and Bulk API chunks can deliver all 200 together, so every trigger and test should assume a full list rather than a single record.
Can I catch a LimitException in Apex?
No. A try-catch block cannot handle a limit exception, and the transaction rolls back. Check usage proactively with Limits.getQueries() and Limits.getLimitQueries(), and design code to stay well below each cap.
Should I use a Flow or an Apex trigger?
Use a Flow for simple declarative logic that admins maintain. Use Apex for unit-tested bulk behavior, complex maps, or callouts. Both share per-transaction limits, so neither is safe when it queries inside a loop.
When should I use Queueable instead of Batch Apex?
Use Queueable for small follow-up jobs started by a transaction. Use Batch Apex for large record sets, because limits reset for each batch execution. Queueable runs as one asynchronous transaction with higher caps than synchronous code.
Top comments (0)