In Salesforce SOQL, a Selective Query is a query that efficiently uses indexes to return a small subset of records, avoiding full table scans and staying within governor limits (especially the 100,000-row limit).
✅ What Is a Selective Query?
A selective query is one that:
-
Uses indexed fields in the
WHEREclause -
Returns a small result set
-
Avoids performance issues or timeouts during execution
๐ซ Non-Selective Query (Bad Example)
-
%John%disables index usage -
Can trigger Too many query rows: 100001
✅ Selective Query (Good Example)
-
AccountIdis an indexed field -
Returns limited records
๐ Selectivity Rule of Thumb
For standard or custom objects:
-
For a query to be selective, it should filter on an indexed field and return:
-
< 10% of records (if > 1 million records)
-
< 100,000 total rows returned
-
๐ Indexed Fields (Default)
| Type | Examples |
|---|---|
| Standard | Id, Name, OwnerId, CreatedDate |
| Custom | Fields marked as External ID or Unique |
| System-created | RecordTypeId, MasterDetailId, LookupId |
You can also request a custom index from Salesforce Support.
๐ ️ Tools to Analyze Query Selectivity
-
Query Plan Tool in Developer Console:
-
Shows if the query is selective
-
Use:
Query Plantab after pasting a SOQL query
-
-
Explain Plan in Workbench:
-
Go to Utilities → Query Plan
-
Paste SOQL to check cost & cardinality
-
๐ง Tips to Make Queries Selective
-
Use indexed fields in filters
-
Use
=orINoperators (not!=,NOT IN, orLIKE '%abc') -
Avoid filtering on formula fields (not indexable)
-
Use skinny tables or custom indexes for reporting-heavy orgs
-
Always bulkify Apex logic around SOQL
No comments:
Post a Comment