Salesforce SOQL Optimization Tips
Salesforce Object Query Language (SOQL) is a powerful mechanism for retrieving data from the Salesforce platform. As organizations scale, the volume of data increases, and inefficient SOQL queries can easily lead to governor limit violations, excessive CPU time, sluggish performance, and deployment challenges. To avoid these issues, developers must follow best practices that ensure queries are optimized and maintainable.
This article discusses practical SOQL optimization techniques that improve speed, reduce resource consumption, and support enterprise-grade application performance.
Understand Salesforce Governor Limits
Before diving deeper, it is essential to understand why SOQL optimization matters. Salesforce enforces strict governor limits to maintain shared instance integrity. These limits include maximum SOQL queries per transaction, maximum records returned, and CPU time limits. By optimizing SOQL, developers remain within these constraints and ensure reliable operations, especially when handling bulk data.
Use Selective Filtering in WHERE Clauses
One of the most common optimization techniques in SOQL is to use selective filters. A selective query filters records efficiently through indexed fields and avoids full table scans. Salesforce considers a filter selective when it reduces the queried dataset significantly.
Filters that support selectivity include:
-
Id
-
Name
-
OwnerId
-
Lookup fields
-
External IDs
-
Audit fields such as CreatedDate
Creating custom indexes through Salesforce support can further improve performance when querying large datasets.
Avoid SELECT *
Salesforce does not support wildcard selection, but developers often query all fields unintentionally by selecting more fields than needed. Querying unnecessary fields increases heap size usage and reduces performance.
Always retrieve only required fields:
This practice improves execution time and prevents excessive payload usage.
Use Efficient Operators
The choice of filter operators affects performance. Operators such as equals (=), IN, and LIKE with a prefix are typically faster than using contains or ends with filters. For example, avoid wildcard search patterns like:
This prevents index-based search and may trigger full scans. Instead, use:
This approach leverages existing indexes and improves execution efficiency.
Avoid Null Checks on Non-Indexed Fields
Checking for null values on non-indexed fields is non-selective and can degrade performance. Developers should use formulas, workflow rules, or indexed fields to avoid null filtering. Alternatively, storing default values ensures the query can target specific conditions without scanning the entire table.
Use LIMIT to Restrict Returned Records
If the use case does not require complete datasets, LIMIT can significantly reduce overhead:
This technique reduces the volume of transferred records, improves response time, and supports lightweight operations.
Reduce Query Count Using Parent-to-Child and Child-to-Parent Queries
Instead of looping through queries repeatedly, use relationship queries. For example, instead of running queries inside loops to retrieve related data, use a single parent-to-child query:
This collects related records efficiently and prevents hitting the governor limit.
Avoid SOQL Queries Inside Loops
Running SOQL inside loops is one of the most common mistakes developers make. This pattern leads to exceeding the maximum SOQL query limit. Always collect ids from looped records, then perform a single bulk query outside the loop. This approach supports bulk processing and avoids resource exhaustion.
Use Query Selectivity Filters on Large Data Volumes
When dealing with millions of records, SOQL performance becomes critical. Salesforce recommends using selectivity thresholds for large objects. Filters should narrow datasets to avoid table scans. Admins can request custom indexing through support for frequently queried fields.
Use Data Skew Strategies
Account data skew arises when many child records are related to a single parent record. This condition leads to locking and delayed execution. Distributing records using ownership diversification, load balancing strategies, and indexed fields mitigates these issues.
Use SOSL When Searching Multiple Fields
If searching across multiple text fields, SOSL can be faster than SOQL. SOSL is optimized for text search and returns results efficiently across objects. Instead of multiple SOQL statements, a single SOSL query can retrieve matches quickly. This reduces query count and execution time.
Leverage Caching with Platform Cache
Repeated SOQL queries in the same request unnecessarily consume query limits. By caching frequently accessed data, developers reduce SOQL usage and improve performance. Platform Cache can temporarily store small datasets and eliminate redundant queries.
Monitor Query Performance Through Developer Tools
Salesforce provides tools such as:
-
Query Plan Tool
-
Developer Console
-
Debug Logs
The Query Plan Tool helps assess:
-
Cardinality
-
Cost of execution
-
Index utilization
Queries with low cost and indexed filters execute faster and are more scalable.
Use Skinny Tables for Large Objects
A skinny table is a physical copy of frequently accessed fields that improves performance through reduced column size. While this is a Salesforce-managed feature, it can dramatically speed up queries under large data loads. Skinny tables are particularly helpful for objects exceeding millions of rows.
Avoid Querying Unnecessary Objects
Review business logic before querying multiple objects. Many queries can be consolidated, especially when relationships exist. Reducing the number of queried objects helps preserve limits and improve clarity.
Defer Complex Data Processing to Async Mechanisms
When processing large datasets, asynchronous processing helps avoid synchronous transaction limits. Techniques include:
-
Batch Apex
-
Scheduled Apex
-
Queueable Apex
Instead of loading large sets at once, execute data in controlled chunks, ensuring reliability and limit compliance.
Optimize Joins and Relationship Queries
When joining objects, developers should minimize nested depth and avoid unnecessary related fields. Excessive join depth can slow down query execution and increase complexity. Limiting relationship depth improves readability and performance.
Use Indexed Formula Fields Where Necessary
Sometimes filtering requires formulas. In such cases, Salesforce can index formula fields on request. Indexed formulas make queries selective and improve performance. However, formula complexity should be kept minimal to avoid slower runtime evaluations.
Conclusion
Optimizing SOQL queries is essential for maintaining high performance and scalability in Salesforce applications. By using selective filters, limiting payloads, avoiding queries inside loops, and leveraging indexes, developers can build reliable and efficient solutions that scale with enterprise growth. Combining performance analysis tools, asynchronous processing, and good schema design ensures long-term maintainability and reliability in high-volume organizations.