Thursday, January 4, 2024

Error: System.LimitException: Too many SOQL queries: 101

 Understanding the Error:

  • Definition: This error occurs when your Apex code attempts to execute more than 100 SOQL (Salesforce Object Query Language) queries within a single execution context.




  • Governor Limits: Salesforce enforces governor limits to safeguard platform performance and resource allocation.

Root Causes:

  • Loops with SOQL Queries: Repetitive queries within loops quickly consume the limit.
  • Unoptimized Triggers: Triggers handling bulk data operations without bulkification can trigger excessive queries.
  • Excessive Sub-selects: SOQL queries within other SOQL queries count towards the limit.
  • Insufficient Code Optimization: Inefficient code structure and query execution can contribute.

Solutions:

  1. Eliminate SOQL Queries Within Loops:

    • Pre-fetch data into collections or maps before loops.
    • Use efficient data retrieval methods like containsKey in maps.
  2. Bulkify Triggers:

    • Employ for loops and bulk DML operations to process multiple records at once.
    • Implement checks like Trigger.isExecuting and Trigger.isUpdate to prevent recursion.
  3. Utilize @future Methods:

    • Offload tasks with intensive SOQL usage to @future methods, which have separate governor limits.
  4. Consolidate Queries:

    • Combine multiple queries into fewer, more efficient ones using relationships and subqueries.
    • Avoid redundant queries for data already in memory.




  5. Adhere to SOQL Best Practices:

    • Query only necessary fields using SELECT clauses.
    • Utilize indexes for faster query execution.
    • Minimize sub-selects.

Additional Tips:

  • Review Code Thoroughly: Identify potential SOQL query overuse and refactor accordingly.
  • Leverage Developer Tools: Use the Developer Console to analyze SOQL queries and pinpoint optimization opportunities.
  • Explore Alternatives: Consider Declarative Lookup Rollup Summaries (DLRS) or external integrations for data retrieval when applicable.



Remember:

  • Synchronous contexts have a SOQL query limit of 100, while asynchronous contexts have a limit of 200.
  • Prioritize code optimization for efficient query usage and application performance.

No comments:

Post a Comment

Please do not enter any spam link in the comment box.