Too many SOQL queries : 101
This error pops up when we hit the 100 SOQL limit governor limit in Apex.
Reason - The main reason for Too many SOQL queries: 101 to show up is using SOQL query in the for loop.
Solution - There are a couple of solutions as to how we can resolve this.
We need to make sure our code follows best practices in Apex Programming, to be even more precise we need to check if there are any queries in for loop and we need to get it out of the loop.
In the process of getting the query out of the loop, we also need to make sure the business logic remains intact, using collections in Apex.
Here is some sample code that is used to get individual accounts and their associated contacts.
We can do the same thing very easily using inner queries, but I wanted to demonstrate how to put queries out of loops along with collections to build a solution that follows best Practices in Apex so that we can avoid, Too many SOQL queries : 101.
We can make use of Async Apex (something like @future, queueable apex) and run part of the business logic in a different thread.
Since Async Apex has a different set of governor limits and also since they run in a different thread, we can avoid hitting the governor limits.
In case you are looking for some complex scenarios in batch apex, this might be helpful
- Batch Apex, Inner Queries and Iterators
- REST API in Batch Apex, errors and maintain state
Hope this is helpful!