Performance

SOQL Selective Queries

Selective Queries

SOQL selective queries use indexed fields for performance.

Understanding SOQL Selective Queries

SOQL (Salesforce Object Query Language) selective queries are essential for optimizing the performance of your database operations in Salesforce. By leveraging indexed fields, selective queries can significantly reduce the query execution time, especially when dealing with large datasets. This article will guide you through the principles of selective queries and how to implement them effectively.

What Makes a Query Selective?

A query is considered selective when it filters results using indexed fields, and the filter criteria return a small subset of the total records. Salesforce defines a query as selective if it returns less than 10% of the total records or fewer than 200,000 records, whichever is smaller. Selective queries are crucial to avoid performance issues and governor limits.

Using Indexes in Selective Queries

Indexes play a pivotal role in making a query selective. Standard fields like Id, Name, and Email are automatically indexed. For custom fields, you can create custom indexes. Using indexed fields in your WHERE clauses can improve query performance significantly.

Best Practices for Writing Selective Queries

  • Use Indexed Fields: Always use indexed fields in your WHERE clause to ensure selectivity.
  • Limit the Result Set: Use LIMIT clauses to restrict the number of records returned.
  • Avoid Negative Filters: Avoid using NOT EQUAL TO (!=) or NOT IN clauses, as these are not selective.
  • Use Query Plans: Use the Query Plan tool in Salesforce to analyze and optimize your queries.

Analyzing Query Selectivity with Query Plan

The Query Plan tool in Salesforce helps you understand the selectivity of your queries. It provides insights into whether your query is using indexes and estimates the cost of the query. This tool is invaluable for optimizing your queries and ensuring they are as efficient as possible.

To use the Query Plan tool, navigate to the Developer Console, enter your query, and click on 'Query Plan'. Review the output to see which parts of your query are selective and identify potential improvements.