Intermediate 30 min read

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];

A selective query's WHERE clause narrows the search down to a small percentage of the object's total records, using a field the database has indexed. 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%'];

A small org's data rarely exposes this problem — but on an object with millions of records, a non-selective query (especially a LIKE '%...%' pattern, which can't use most indexes at all) can simply time out rather than ever completing. 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.

APEX

Query Selectivity and Performance Quiz

1. What makes a SOQL query "selective"?

Log in to submit the quiz and save your score.

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.