Thursday, April 30, 2026

Too many SOQL queries: 101

 

✅ Best Practices to Avoid Limit Exception

1. Move SOQL outside loops (Bulkification)

Set<Id> accIds = new Set<Id>();
for(Account acc : accounts){
accIds.add(acc.Id);
}

Map<Id, List<Contact>> accContactMap = new Map<Id, List<Contact>>();

for(Contact con : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accIds]){
if(!accContactMap.containsKey(con.AccountId)){
accContactMap.put(con.AccountId, new List<Contact>());
}
accContactMap.get(con.AccountId).add(con);
}

✔ Only 1 query instead of many


2. Use Maps for Fast Lookup

Avoid repeated queries—store data in Map<Id, Object>

Map<Id, Account> accMap = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accIds]
);

3. Avoid SOQL in Triggers (use Handler Class)

Structure your trigger properly:

trigger AccountTrigger on Account (before insert, before update) {
AccountHandler.handle(accounts);
}

4. Use Relationship Queries

Instead of multiple queries, use child relationships

List<Account> accs = [
SELECT Id, Name, (SELECT Id, Name FROM Contacts)
FROM Account
];

✔ Fetch parent + child in one query


5. Use Collections (Set, Map) Efficiently

  • Use Set to remove duplicates
  • Use Map for key-based access

6. Check Recursive Triggers

Sometimes triggers call themselves and cause repeated queries.

public class TriggerHelper {
public static Boolean isRunning = false;
}

7. Use @future / Queueable for Heavy Logic

If logic is too heavy:

@future
public static void processData(Set<Id> recordIds){
// async processing
}

✔ Runs in separate transaction → fresh limits


8. Use Limits Class (Debugging)

System.debug('Queries used: ' + Limits.getQueries());
System.debug('Limit: ' + Limits.getLimitQueries());

🔧 Common Real-World Fix Pattern

❌ Bad:

for(Opportunity opp : oppList){
Account acc = [SELECT Id FROM Account WHERE Id = :opp.AccountId];
}

✅ Good:

Set<Id> accIds = new Set<Id>();
for(Opportunity opp : oppList){
accIds.add(opp.AccountId);
}

Map<Id, Account> accMap = new Map<Id, Account>(
[SELECT Id FROM Account WHERE Id IN :accIds]
);

No comments:

Post a Comment