How to Resolve System.limitException: Too many SOQL Queries 101

In Salesforce we got the System.limitException: Too many SOQL Queries 101 very often. In this post, we will learn what is this exception and how to avoid Too many SOQL Queries 101 in Salesforce.

What is Too many SOQL Queries 101 Exception?

In Salesforce we can encounter the Salesforce Governor Limits system limit exception too many soql queries 101 very often. This means we can only have up to 100 SOQL in a single context. This is a hard limit, which means you can’t increase it by contacting Salesforce support.

The following error appears when we exceed the Governors Limit.

System.LimitException: Too many SOQL queries: 101 error

As per the governor limit, the Total number of SOQL queries issued is 100 in Synchronous and 200 in Asynchronous context.

When Too many SOQL Queries 101 error appear

Here is one example of code that can introduce Too many SOQL query errors when you will try to insert more than 200 records in Salesforce.

For(Account acc: Trigger.new){
 for(Contact con:[select id from contact where accountId = :acc.Id]){
 }
}

When you will try to execute the above code with more than 200 records you will get a System limit exception. which you can find in debug log.

Too many SOQL Queries 101 error

Why we will get SOQL 101 error? Because we are using SOQL query inside the for a loop.

Reason for SOQL Queries 101 error

Let see the all other reason for SOQL 101 Error.

  • Soql inside the for Loop
  • A Trigger is not bulkified.
  • Trigger is recursive
  • Multiple processes are executing at the same time and updating the same record in the same transection.

Let’s see how to resolve this System.LimitException: Too many SOQL queries error.

How to Resolve the “Too many SOQL queries: 101” error?

Let see how to resolve this System.LimitException: Too many SOQL queries: 101 error.

  • Do not have DML statements or SOQL queries in our FOR loop.
  • Use the collection to avoid SOQL inside the for loop
  • Bulkify Apex Trigger and follow Trigger framework to avoid the recursive issue in your code
  • Potentially move some business logic into @future.
  • Since the database time is not calculated in CPU time it is always better to explore the usage of aggregate SOQL for your business use case.
  • Follow the key coding principles for Apex Code.

Let see the solutions in details

1. Avoid SOQL queries inside For Loop

Do not place SOQL or DML(insert/update/delete/undelete) statements inside a loop. When these operations are placed inside a for loop, database operations are invoked once per iteration of the loop making it very easy to reach these SFDC governor limits.

Here is an example of putting SOQL Query outside of for loop.

Map<Id, Account> accountMap=new Map<id, Account>([select id,name, (select id from contacts) from account where id in:trigger.newmap.keyset()]);

for(Account acc: accountMap.values()){
	For(Contact con:acc.Contacts){ 
	}
}

2. Bulkify Apex Trigger and Recursion Handling

One of the very common issues for Too many SOQL Queries 101 is when your trigger is not written as per best practices and multiple triggers are created on a single object. We should write scalable code and avoid hitting the governor.

2.1 Recursion Handling

Bulky Apex Trigger and follow the Trigger framework to avoid the recursive issue in your code.

3. Move some business logic into @future

Apex written within an asynchronous method gets its own independent set of higher governor limits. For example, the number of SOQL queries doubles from 100 to 200 when using asynchronous calls. The total heap size and maximum CPU time are similarly larger for asynchronous calls.

4. Minimize the No.of SOQLs by merging the queries

we will merge the SQL query of single object in a single query if possible. For Example:

Opportunity op = [select StageName, Account.OwnerId From Opportunity where id: opId];

List olis = [select id, productId from OpportunityLineItem where OpportunityId =: op.Id];
Account acc = [Select name, id from Account where id = :accid];

List<Contact> lstConts = [Select firstName,LastName from Contact where accountid = :accid];

Change it to:

Account acc = [Select Id, Name, (Select id, firstName,LastName from Contacts) From Account where id = :accid];

FAQ

What is the SOQL query Limit in Salesforce

100 in the Synchronous process and 200 in the Asynchronous process.

What does too many SOQL queries mean?

This means we can only have up to 100 SOQL in a single context. This is a hard limit, which means you can’t increase it by contacting Salesforce support

How to improve SOQL performance?

For best performance, SOQL queries must be selective. You may receive an error message when a non-selective query in a trigger executes against an object that contains more than 100,000 records. To avoid this error, ensure that the query is selective. Check out SOQL Best Practices.

How do I fix error 101 SOQL?

Apex written within an asynchronous method gets its own independent set of higher governor limits/ Use @future method to fix the issue.

Summary

I hope this post helped you to understand what is Too Many SOQL queries issue is and how to fix it.

Amit Chaudhary
Amit Chaudhary

Amit Chaudhary is Salesforce Application & System Architect and working on Salesforce Platform since 2010. He is Salesforce MVP since 2017 and have 17 Salesforce Certificates.

He is a active blogger and founder of Apex Hours.

Articles: 460

10 Comments

  1. Recently I passed a super badge APEX Specialist, and in one of the challenges, a potential pitfall was a “Too many SOQL queries” exception.
    The remedy is exactly as Mr. Chaudhary suggests:
    – Avoid SOQL queries in a loop, instead perform a query and loop over the results.
    – Don’t commit your changes in a loop, instead fill a structure (eg. List ) and after all insert the created structure, which will count as just one DML query.

    • Salesforce doesn’t count subqueries against governor limit of 100 SOQLs. It counts only root query which means only 1 SOQL query would be consumed

  2. when i make transaction, more number of methods been called and i am not sure which method is triggering more soql queries. is there anyway to see this method has executed these many queries ?

  3. Two users having same Profile , Role and Permissionset Groups, but once user is getting “Too many SOQL Queries 101” error. what could be the reason

Leave a Reply

Your email address will not be published. Required fields are marked *