Skip to content
Latchkey

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.

sf
System.LimitException: Too many SOQL queries: 101
Class.OrderService.recalc: line 42, column 1

Common 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

  1. Move the SOQL out of the loop and query the full set at once.
  2. Build a map keyed by ID and look up inside the loop instead of querying.
  3. Re-run the test with a bulk data set to confirm it stays under the limit.
Apex
// 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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →