Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    • Enhancing Performance with File Compression in Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Sunday, May 11
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Apex»Optimize SOQL Filter in Apex Code

    Optimize SOQL Filter in Apex Code

    Dhanik Lal SahniBy Dhanik Lal SahniFebruary 2, 2022Updated:June 12, 20237 Comments6 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Optimize SOQL Filter in Apex Code
    Share
    Facebook Twitter LinkedIn Pinterest Email

    We create new custom applications in Salesforce or customize the existing applications using custom code like Visual Force Page, Aura component, LWC component, and Apex code. While creating custom code, we need to keep in mind application/page/component performance. For better performance data retrieval is one of the major factors. Our query should be selective for better performance. This post will explain how to optimize SOQL filter in apex code to make it selective.

    Before we move ahead, let us first see what is selective query in Salesforce. As per Salesforce documentation

    A query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting number of rows below a system-defined threshold.

    It means we should add at least one filter criteria in SOQL which is on the index field. By default, we have the following standard fields which are index fields.

    • Primary keys – Id, Name, and OwnerId fields
    • Foreign keys – CreatedById, LastModifiedById, lookup, master-detail relationship fields
    • Audit dates – CreatedDate and SystemModstamp fields
    • RecordType fields – Indexed for all standard objects
    • Custom fields that are marked as External ID or Unique

    We should add one of these fields in SOQL filter criteria to make it selective. In case our query is returning huge records even after applying these selective indexes then we should also handle the maximum threshold limit of returned records. Let us see this maximum threshold limit concept in detail.

    Below is rule to identify what is maximum threshold for any selective query

    1. For a standard index, the threshold is 30 percent of the first million targeted records and 15 percent of all records after that first million.
    2. The maximum threshold limit for the standard index is 1 million records which will be reached when we have 5.6 million records in total
    3. For a custom index, the selectivity threshold is 10 percent of the first million targeted records and 5 percent of all records after that first million.
    4. The maximum threshold limit for the custom index is 333,333 records which will be reached when we have 5.6 million records in total

    Standard Index Threshold

    The below image is showing the maximum threshold for the query results for the standard index.

    SQOL Selective Query | Standard Index Query Optimization | SQOL Optimization | Apex Optimization

    So take an example we have below query to fetch Opportunity records

    SELECT Id FROM Opportunity  WHERE CreatedDate = THIS_YEAR

    On the basis of the above query here is the maximum threshold for this query to become selective.

    SQOL Selective Query | Standard Index Query Optimization | SQOL Optimization | Apex Optimization

    So if our Opportunity has 3,43,329 records then the maximum threshold will be 102,999. If we have 80,000 records for last year in Opportunity object then it will be under our maximum threshold. So this index on a created date is selective and optimized by a query analyzer. If last year’s opportunity record is beyond 102,999 then it will exceed the maximum threshold, so the query will not be optimized.

    If our Opportunity has 24,33,290 records then the maximum threshold will be 5,14,993. If we have 180,000 records for last year in Opportunity object then it will be under our maximum threshold. So this index on a created date is selective and optimized by a query analyzer. If same time we have 6,00,009 records in Opportunity last year then it will exceed the maximum threshold and not be optimized.

    Custom Index Threshold

    In some situations standard index is not used in SOQL in that case we should get a custom index created. This is required when we run SOQL for reporting or batch processing. Custom index is created by the Salesforce Support team, so if you need it then create a case with complete requirement detail.

    The below image is showing the maximum threshold for the query results for the custom index.

    SQOL Selective Query | Custom Index Query Optimization | SQOL Optimization | Apex Optimization

    So take an example we have below query to fetch Opportunity records. Status__c field is custom indexed.

    SELECT Id FROM Opportunity  WHERE Staus__c= 'Closed'

    On the basis of the above query here is the maximum threshold for this query to become selective.

    SQOL Selective Query | Custom Index Query Optimization | SQOL Optimization | Apex Optimization | optimize soql

    So if our Opportunity has 3,43,329 records then the maximum threshold will be 34,332. If we have 80,000 records for last year in Opportunity object then it will be under our maximum threshold. So this index on a Status field is selective and optimized by a query analyzer. If the opportunity record is beyond 34,332 then it will exceed the maximum threshold, so the query will not be optimized.

    If our Opportunity has 24,33,290 records then the maximum threshold will be 1,17,664. If we have 1,80,000 closed records in the Opportunity object then it will be under our maximum threshold. So this index on a Status field is selective and optimized by a query analyzer. If at the same time we have 6,00,009 records in Opportunity which are closed then it will exceed the maximum threshold and not be optimized by the optimizer.

    Both Standard and Custom Index in query

    • If both standard and custom indexes are used in SOQL filters then the system will use an index that is under the threshold and it will be a selective query.
    • If both standard and custom indexes are used in SOQL filters and both are under threshold then a cost-effective index will be used.
    • If both indexes are returning records beyond the maximum threshold then that query will not be selective and not optimized.

    Is index always required in SOQL?

    We should always try to use one index in the SOQL query especially where we are querying a large set of records for batch processing or report creation.

    Even we have a configuration object or small object, there also we should use an index. What we can do is, we can create a default record type in the configuration object and use that in SOQL. This way queries will be optimized.

    What should avoid in SOQL Filter?

    We should avoid the below points for making query selective.

    • We should avoid !=null (not equal to null) condition in where clause
    • Avoid wildcard (‘%salesforce%’) condition. Instead of this, SOSL is a better fit in most the situation
    • Avoid null in contains like a city in (‘Delhi’,’Mumbai,null)

    Summary:

    SOQL is important for application performance. Our query should be selective always to optimize it. For this. try to use standard index, if that is not fitting to your use case and huge records are returning then get custom index created from Salesforce Support. Try to avoid nulls in filter conditions.

    Similar Posts:

    Optimizing Salesforce Apex Code

    Optimizing Loop in Apex Code

    Optimize Code by Disabling Debug Mode

    Optimize Apex Code by Metadata Caching

    Referenced Posts for Optimize soql:

    Make SOQL query selective

    Working with Very Large SOQL Queries

    apex application performance code optimization non selective query Optimize SOQL selective query soql soql optimization SOQL performance
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleOptimize Apex Code by Metadata Caching
    Next Article Cuttly Url Shortener in Salesforce
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    Top 10 Salesforce Flow Features of Salesforce Summer ’25

    May 11, 2025
    By Dhanik Lal Sahni6 Mins Read

    Unlock the Power of Vibe Coding in Salesforce

    April 30, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Dynamic Queueable Chaining in Salesforce Apex

    April 21, 2025
    View 7 Comments

    7 Comments

    1. Akhila on February 7, 2022 4:34 pm

      Nice read, indeed helpful

      Reply
      • Dhanik Lal Sahni on February 15, 2022 8:24 pm

        Thank You Akhila.

        Reply
    2. Pingback: Cuttly Url Shortener in Salesforce | SalesforceCodex

    3. Pingback: Queueable Vs Batch Apex In Salesforce - Salesforce Codex - Stories

    4. Pingback: Optimizing Salesforce Apex Code | SalesforceCodex

    5. Pingback: Best Practices to Avoid Hardcoding in Apex | SalesforceCodex

    6. Pingback: How to Manage Technical Debt in Salesforce | SalesforceCodex

    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) einstein (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex (3) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (140) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) einstein (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex (3) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (140) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.