Performance

SOQL Query Limits

Managing Query Limits

SOQL query limits enforce governor restrictions in Salesforce.

Introduction to SOQL Query Limits

Salesforce Object Query Language (SOQL) is a powerful tool for querying data within Salesforce. However, to ensure system stability and performance, Salesforce enforces certain governor limits on SOQL queries. These limits are designed to prevent any single query from consuming excessive resources, which could impact the performance of the Salesforce platform for other users.

Understanding Governor Limits

Governor limits are set by Salesforce to ensure that shared resources are used efficiently and equitably. These limits apply to both synchronous and asynchronous queries and include restrictions on the number of queries, the amount of returned data, and the complexity of the queries themselves.

Key SOQL Query Limits

  • Total Number of SOQL Queries: You can execute up to 100 SOQL queries in a single transaction for synchronous Apex, and up to 200 for asynchronous Apex.
  • Number of Records Retrieved: You can return up to 50,000 records in a single query.
  • Total Query Rows: You can retrieve up to 50,000 rows using SOQL queries within a single transaction.
  • Query Performance: Queries that take more than 120 seconds to execute will be terminated.

Best Practices for Managing SOQL Query Limits

To effectively manage SOQL query limits and optimize performance, consider the following best practices:

  • Selective Queries: Use filters and conditions to ensure that your queries are selective and return only the necessary data.
  • Avoid Nested Queries: Minimize the use of nested queries, which can increase complexity and execution time.
  • Use Query Planning: Leverage Salesforce's query planning and optimization tools to analyze and improve query performance.
  • Indexing: Ensure fields used in WHERE clauses are indexed to speed up query execution.

Example of a SOQL Query

This SOQL query retrieves the Id and Name of Account records where the Industry is 'Technology'. The LIMIT 100 clause ensures that the query does not exceed the number of records allowed for retrieval in a single transaction.

Handling Query Limit Errors

When a query exceeds the SOQL limits, Salesforce throws a runtime exception. To handle these errors effectively, use exception handling mechanisms such as try-catch blocks in Apex to gracefully manage these situations and provide alternative solutions or user feedback.

In this example, we attempt to execute a SOQL query and handle any exceptions that occur if the query exceeds the limits. This ensures that the application can continue to function smoothly, even when encountering runtime errors.