How to avoid Error: "Too many SOQL queries: 101"
- I am hitting salesforce limits in 3 cases:
There are two Opportunities that will show the error above:
When a user is adding a document from a large list of docs which is greater than 100? (Eg error when they are trying to pull a document from their library that has 196 documents) When processing a list of ATTACHMENTS greater than 100. When an Opportunity has 100 contacts, the controller throws an error. Opportunity "Opp with 100 Contacts 1 Document", if we click on the custom button on action. Opportunity "Opp with 1 Contact 102 Documents", if we click on the custom button on action.
To avoid Error: "Too many SOQL queries: 101"
- Avoid SOQL queries that are inside FOR loops.
- Make sure you don't have a recursive loop calling a SOQL.
- Do not do any DML/CRUD inside a for loop.
Avoid more than one DML on a single object in a single transaction - because each DML invokes triggers of related objects can cause addition of SOQL count.
Avoid too many field updates in process builders in different conditional branches. Each branch runs a DML and initiates trigger execution.
If there are a lot of business processes and logic in your trigger then design and isolate processes with help of future and batch if needed.
Recursion Handling - To ensure a trigger is not running recursively.
Minimize the No.of SOQLs by merging the queries - we will merge the SQL query of a 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];
Change it to:
Opportunity op = [select StageName, Account.OwnerId, (select id, productId from OpportunityLineItems) From Opportunity where id: opId];