Too many SOQL queries: 101" salesforce error
Fixes Salesforce 'Too many SOQL queries: 101': code runs queries inside a loop instead of bulkifying. Move queries out of loops, collect ids first, and query once. Use when Apex or flows hit the 101-query governor limit. Not for API daily limits.
TL;DR
Something runs a SOQL query per record instead of once for all records, and the 101-query transaction limit stops it. Collect the ids first, run one query with an IN clause, and map results back. The fix is structural, not a limit increase.
Error
System.LimitException: Too many SOQL queries: 101Steps
- Get the debug log and find the repeated query; it usually sits inside a for loop over Trigger.new or a batch. Expected: you see the same query shape dozens of times.
- Before the loop, collect the ids into a set. Expected: one set holding every id the loop needs.
- Replace the in-loop query with a single query using WHERE Id IN :idSet, stored in a map. Expected: one query total regardless of batch size.
- Inside the loop, read from the map instead of querying. Expected: identical logic, 1 query instead of N.
- Re-run with 200 records (the trigger batch size). Expected: no limit exception and correct results.
When to use
- Apex throws System.LimitException: Too many SOQL queries: 101.
- A flow with a "Get Records" inside a loop fails on bulk data.
- An agent calls the query API once per record and hits limits.
When not to use
- REQUESTLIMITEXCEEDED (API daily limits, different fix).
- "Too many DML statements" (same pattern, but for writes).
Tool compatibility
- Salesforce Apex triggers, batch classes, and flows.
- Agents that should use one bulk query instead of N single queries.
Variant phrasings
System.LimitException on queries
The exception form; the count in the message shows how far over the limit it went.
flow fails with too many queries
A Get Records element inside a loop; move it before the loop.
Why it happens
The governor limit counts queries per transaction (101 synchronous). Code tested with one record works; the same code with 200 records runs the loop 200 times and dies.
Edge cases
- Triggers that call helper methods which each query: the loop is hidden one call down; bulkify the helper.
- Flows can query in loops invisibly; the debug log shows the count climbing.
- Future methods and queueables get fresh limits; moving work async is a valid fallback, not the first fix.
Provenance
Resolved from the public thread: https://vectle.com/posts/pstDXSuP4vhbo3ItzVDeeSjg
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.