A trigger works in the UI but fails with 'Too many SOQL queries: 101' during a data load. Walk me through the fix.
Your confidence:Not rated
Model answer
- Reproduce with a test that inserts or updates 200+ records. The UI saves one record, the load sends chunks of 200.
- Find the cause in the debug log (
SOQL_EXECUTE_BEGINcounts) or by reading the code. Typical causes:- a query inside a
forloop overTrigger.new; - a helper method that queries and is called per record;
- recursion: the trigger updates records that fire the trigger again;
- other automation in the same transaction (flows, other triggers) adding queries.
- a query inside a
- Fix with the set-and-map pattern: collect IDs, one query, a map for lookups, one DML per object. Move per-record helper queries into bulk methods.
- Guard recursion by tracking processed records per event, not with a blunt static boolean.
- Check the whole transaction: use
Limits.getQueries()in tests to assert headroom, and review flows on the same object. - Prevent regressions: keep the bulk test, and add a code review rule ("no SOQL or DML in loops") plus static analysis (PMD rules) in CI.
โ Key points to hit
โ Red-flag answers
- Asking for a limit increase
- Wrapping the query in try/catch
- Reducing the data-load batch size as the permanent fix
โช Follow-ups
Can you catch a LimitException?
No. Governor limit exceptions can't be caught. You must design to stay under the limits, or move work to async contexts with higher limits.
How do you find which automation used the queries?
The debug log shows code units in order (triggers, flows, validation) with their SOQL and DML. Filter by CODE_UNIT_STARTED and SOQL_EXECUTE_BEGIN, or use the Apex Log Analyzer to see the call tree and counts.