Query Selectivity and Performance
By the end of this lesson, you'll be able to:
- Explain what makes a query selective
- Recognize why an indexed field speeds up a filter condition
- Identify a non-selective query that could time out on a large object
Prerequisites: "Dynamic SOQL and Injection Risk"
What makes a query selective
// Selective: Id is always indexed, and this matches very few records
List<Account> account = [SELECT Id FROM Account WHERE Id = :specificId];
// Potentially non-selective: matches a large fraction of all records
List<Account> accounts = [SELECT Id FROM Account WHERE Industry != null];
// Selective: Id is always indexed, and this matches very few records— the label for the good example.List<Account> account = [SELECT Id FROM Account WHERE Id = :specificId];— a selective query'sWHEREclause narrows the search down to a small percentage of the object's total records, using a field the database has indexed.- (blank line)
// Potentially non-selective: matches a large fraction of all records— the label for the risky example.List<Account> accounts = [SELECT Id FROM Account WHERE Industry != null];— a query whose filter matches most of an object's records isn't selective, no matter how the query is written.
Why indexed fields matter
Just like a book's index lets you jump straight to a topic instead of reading every page, an indexed database field lets Salesforce jump straight to matching records instead of scanning the entire table. Id and external Id fields (Module 19) are indexed automatically; other fields can be indexed by an admin when a query pattern needs it.
Why this matters at real scale
// On an object with 5 million records, this could time out
List<Account> accounts = [SELECT Id FROM Account WHERE CustomText__c LIKE '%import%'];
// On an object with 5 million records, this could time out— the scale that exposes the problem.List<Account> accounts = [SELECT Id FROM Account WHERE CustomText__c LIKE '%import%'];— a non-selective query, especially aLIKE '%...%'pattern (which can't use most indexes at all), can simply time out rather than ever completing at that scale.
A small org's data rarely exposes this problem — this is why query performance, easy to ignore in a small dev org, becomes a real, load-bearing concern in production at scale.
Exercise
As a comment, explain why WHERE Id = :specificId is selective, but WHERE Industry != null likely is not.
Show hint
Think about what fraction of total records each condition would match.
Query Selectivity and Performance Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A selective query filters down to a small fraction of an object's total records using indexed fields — non-selective queries on very large objects can time out entirely.