Governor Limits in Salesforce – Explained with Examples
Salesforce runs on a multi-tenant architecture, meaning resources are shared across all users. To ensure fair usage, Salesforce enforces Governor Limits. These limits restrict how much data and how many operations your code can perform.
Why Are Governor Limits Important?
If your code exceeds any of these limits, Salesforce throws a runtime exception, and the operation fails. So, understanding and respecting these limits is essential for writing scalable and safe Apex code.
Common Apex Governor Limits
- SOQL Queries: 100 queries per transaction
- DML Statements: 150 statements per transaction
- Records Retrieved by SOQL: 50,000 records
- Records Processed by DML: 10,000 records
- CPU Time Limit: 10,000 ms (synchronous)
Bad Practice: Exceeding SOQL Limit
// BAD: SOQL inside loop
for(Account acc : accList) {
Contact[] cons = [SELECT Id FROM Contact WHERE AccountId = :acc.Id];
}
This causes SOQL to be run multiple times – could easily hit the 100 query limit.
Good Practice: Bulkify with a Single SOQL
// GOOD: SOQL outside loop
Set<Id> accIds = new Set<Id>();
for(Account acc : accList) {
accIds.add(acc.Id);
}
Map<Id, List<Contact>> contactsMap = new Map<Id, List<Contact>>();
for(Contact con : [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accIds]) {
if(!contactsMap.containsKey(con.AccountId)) {
contactsMap.put(con.AccountId, new List<Contact>());
}
contactsMap.get(con.AccountId).add(con);
}
This version avoids SOQL inside the loop and works efficiently in bulk.
Tools to Monitor Limits
Limits.getDmlStatements()
– DML usedLimits.getQueries()
– SOQL usedLimits.getCpuTime()
– CPU time
Governor limits are not enemies – they are guardrails to write better, bulkified, and optimized code. Keep them in mind while coding in Apex to avoid runtime exceptions and ensure smooth performance!