Sub topic 10
Understanding SOQL governor limits
This chapter assumes you can write basic inline SOQL queries, loop over collections, and run Apex in the Developer Console or an IDE. It covers the limits that apply to SOQL, how to measure your usage, and the habits that keep code under those limits.
Why limits exist
Salesforce runs many customers' code on shared infrastructure. Governor limits cap what a single transaction can consume so that one runaway query loop cannot slow down other orgs. A transaction is one unit of work, such as a trigger firing on a save, a button click, or one execution of an anonymous Apex block. All code that runs inside it shares one set of counters. This includes your trigger, other triggers on the same object, flows, and any helper classes they call.
When code goes over a limit, Salesforce throws a System.LimitException. You cannot catch this exception. The transaction stops and all of its database changes are rolled back.
The SOQL limits that matter most
The values below are for synchronous Apex. Check the current Apex Developer Guide for exact numbers, because they can change between releases.
| Limit | Synchronous | Asynchronous (batch, future, queueable) |
|---|---|---|
| SOQL queries issued | 100 | 200 |
| Total records retrieved by SOQL queries | 50,000 | 50,000 |
| Heap size | 6 MB | 12 MB |
Three points about these numbers:
- The query count is the number of SOQL statements that run. It does not matter how many rows each one returns. A query inside a loop that runs 101 times uses 101 queries.
- The row count is the total number of records returned across all queries in the transaction. Two queries that return 30,000 rows each go over the limit even though each one alone is fine.
- Heap is the memory your variables use. A list of records with many fields can hit the heap limit before it hits the row limit.
A parent-to-child subquery, such as SELECT Name, (SELECT LastName FROM Contacts) FROM Account, counts as one query. The child records it returns still count toward the row limit.
The errors you will see are:
System.LimitException: Too many SOQL queries: 101System.LimitException: Too many query rows: 50001System.LimitException: Apex heap size too large
How a query-in-loop failure happens
Triggers receive records in batches of up to 200. If your trigger runs one query per record, a data load of 200 records needs 200 queries. That fails in a synchronous transaction after the 100th query.
This code often passes a manual test, because a user who saves one record uses only one query. It then fails when someone imports a CSV file.
Measuring your usage with the Limits class
The Limits class reports how much of each limit the current transaction has used. Use it while developing and in debug logs.
System.debug('Queries used: ' + Limits.getQueries()
+ ' of ' + Limits.getLimitQueries());
System.debug('Rows retrieved: ' + Limits.getQueryRows()
+ ' of ' + Limits.getLimitQueryRows());
System.debug('Heap used: ' + Limits.getHeapSize()
+ ' of ' + Limits.getLimitHeapSize());
List<Account> accts = [SELECT Id, Name FROM Account LIMIT 5];
System.debug('After one query, queries used: ' + Limits.getQueries());
System.debug('Rows now: ' + Limits.getQueryRows());Run this in anonymous Apex and read the output in the debug log. The numbers change by one query and by the number of rows returned. The getLimit... methods return the maximum for the current context, so the same code reports 100 or 200 depending on how it runs.
You can also read the "Cumulative resource usage" section at the end of a debug log. It lists every limit with used and maximum values.
Do not use Limits to dodge the limit
Some code checks Limits.getQueries() < Limits.getLimitQueries() before querying and skips the query otherwise. This hides the problem and produces wrong results, because the code silently does less work. Use Limits to find the places where you use too many queries, then fix the query design.
Fixing the loop: collect, query once, look up
The standard fix has three steps:
- Loop once to collect the Ids or values you need into a
Set. - Run one query with
IN :set. - Put the results in a
Mapand look values up inside the loop.
public class ContactAccountReport {
public static void log(List<Contact> contacts) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
for (Contact c : contacts) {
Account a = accountsById.get(c.AccountId);
if (a != null) {
System.debug(c.LastName + ' -> ' + a.Name);
}
}
}
}This uses one query whether contacts holds 1 record or 200. The Map constructor that accepts a query result keys each record by its Id for you. The next chapters on bulk-safe patterns build on this.
For some cases you can remove the second query entirely with a relationship query. If you need the account name for each contact, SELECT LastName, Account.Name FROM Contact returns it in one query.
Hidden loops
A query is not always visibly inside a for loop. These patterns have the same effect:
- A helper method that runs a query, called from inside a loop. The loop looks clean, but each call costs one query.
- A trigger on Contact that updates Account records, where an Account trigger then runs more queries. Both triggers share the same counters, so their queries add up.
- Several triggers or automations on one object that each run their own query on every save.
When a limit error appears in a trigger, the debug log shows the line that ran the 101st query. That line is not always the source of the problem. Look at the cumulative usage section and count which statements ran most often.
Staying under the row limit
The 50,000 row limit counts every record returned. A few ways to stay under it:
- Add a
WHEREclause that matches the records you need. Do not query a whole object and filter in Apex. - Select only the fields you need. Each field adds to heap size, and long text fields add a lot.
- Use
LIMITwhen you only need a few records. - Use
SELECT COUNT() FROM Account WHERE ...when you only need a number. Do not query the records and callsize(). - Use an aggregate query with
GROUP BYwhen you need totals, so the database does the summing.
Here is the difference for counting:
// Retrieves every matching record just to count them
Integer wasteful = [SELECT Id FROM Account WHERE Industry = 'Technology'].size();
// Asks the database for the count
Integer efficient = [SELECT COUNT() FROM Account WHERE Industry = 'Technology'];The first form can throw Too many query rows on a large org. The second form does not fail for that reason.
If you really must process more than 50,000 records, the transaction has to be split up. A SOQL for loop keeps heap use down because it fetches records in chunks of 200, but the total rows retrieved still count against the 50,000 limit. For larger volumes, use Batch Apex, which processes records in separate transactions, each with its own limits.
Limits in tests
Test methods run in their own transaction with the same limits. Test.startTest() and Test.stopTest() give the code between them a fresh set of limits. This lets you separate your setup queries from the code you are testing.
A test that checks bulk behavior should insert 200 records and then run the code. It should fail if the code runs a query per record:
@isTest
private class ContactAccountReportTest {
@isTest
static void usesOneQueryForTwoHundredContacts() {
Account acct = new Account(Name = 'Bulk Test Account');
insert acct;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Test' + i, AccountId = acct.Id));
}
insert contacts;
Test.startTest();
ContactAccountReport.log(contacts);
Integer used = Limits.getQueries();
Test.stopTest();
Assert.areEqual(1, used, 'Expected a single query for the whole batch');
}
}If someone later changes log to query inside the loop, this test fails with a clear message. It does not wait for a production data load to find the problem.
Common mistakes
- Testing triggers with one record only. Always test with 200.
- Catching
Exceptionand assuming it handles limit errors. ALimitExceptionpasses throughcatchblocks. - Querying in a constructor or property getter that is called repeatedly. Cache the result in a variable.
- Using
staticcaching without thinking about it. A static variable lives for the whole transaction, which is useful for reusing one query result, but it can hold stale data after an update in the same transaction.
Exercise
A trigger on Contact receives 150 records from a data import. For each contact it runs [SELECT Name FROM Account WHERE Id = :c.AccountId]. The same transaction also runs 10 queries in other code. What happens, and how would you fix the trigger?
Show answer
The trigger needs 150 queries and the other code uses 10, so the transaction reaches 101 queries partway through the loop. In a synchronous transaction it throws an uncatchable System.LimitException: Too many SOQL queries: 101 and everything is rolled back. The fix is to collect the AccountIds into a Set, run one query with WHERE Id IN :accountIds into a Map<Id, Account>, and read from the map inside the loop. That uses one query for the trigger, 11 in total.
Exercise
Why is [SELECT COUNT() FROM Account WHERE Industry = 'Technology'] safer than [SELECT Id FROM Account WHERE Industry = 'Technology'].size() on a large org?
Show answer
The second form retrieves every matching record, so it adds all of them to the 50,000 row total and to heap use, and it can throw Too many query rows. The first form asks the database for the count and returns an Integer without returning the records.