Salesforce "System.LimitException: Too many SOQL queries: 101" in CI
Apex enforces a governor limit of 100 SOQL queries per transaction. Hitting 101 throws System.LimitException, almost always because a query sits inside a loop and runs once per record instead of once in bulk.
What this error means
An Apex test fails with "System.LimitException: Too many SOQL queries: 101", pointing at a query executed repeatedly in a loop.
System.LimitException: Too many SOQL queries: 101
Class.OrderService.recalc: line 42, column 1Common causes
A SOQL query inside a loop
Running a query per record across 100+ records exceeds the per-transaction SOQL limit. The test surfaces it because it processes a realistic batch.
Trigger logic not bulkified
A trigger querying inside a for-each over Trigger.new multiplies queries by record count and trips the limit on bulk operations.
How to fix it
Bulkify: query once outside the loop
- Move the SOQL out of the loop and query the full set at once.
- Build a map keyed by ID and look up inside the loop instead of querying.
- Re-run the test with a bulk data set to confirm it stays under the limit.
// before: query in loop (fails at 101)
// after: query once, map lookups in loop
Map<Id, Account> accs = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :ids]);Bulkify trigger handlers
Aggregate IDs from Trigger.new, run one query for all of them, and process collections rather than querying per record.
How to prevent it
- Never put SOQL inside a loop; query collections once.
- Write tests that insert 200+ records to catch non-bulk code.
- Use maps for related-record lookups instead of per-record queries.