Sub topic 16
Query selectivity and performance
This chapter assumes you can write inline SOQL with WHERE filters and bind variables, and that you know the governor limits on query count and rows. It covers why some queries are fast and others fail or time out, and how to write queries the platform can run efficiently.
What selectivity means
Salesforce stores records for all customers in shared tables. The query optimizer decides how to run each query: use an index on a filtered field, or scan the whole table. A filter is selective when it uses an index and returns a small enough share of the records. A query is selective when at least one of its filters is selective.
On a small object the difference is invisible. On an object with hundreds of thousands or millions of rows, a non-selective query is slow. It can hit the 120-second query timeout. In a trigger on a large object it can fail with Non-selective query against large object type (more than 200000 rows).
Thresholds depend on the kind of index. These are the commonly documented values. Check the current Salesforce documentation for your release.
| Index type | Selective if the filter returns fewer than | Maximum rows |
|---|---|---|
| Standard index | 30% of the first million records, then 15% of the rest | 1,000,000 |
| Custom index | 10% of the first million records, then 5% of the rest | 333,333 |
The percentages apply to the total records in the object. Records in the recycle bin count too.
Which fields are indexed
These fields are indexed by default:
Id,Name,OwnerId,CreatedDate, andSystemModstamp- Lookup and master-detail relationship fields, such as
AccountIdon Contact - Fields marked as an External ID or Unique
RecordTypeIdon most objects
Other fields can be indexed through a custom index, which you request from Salesforce Support. External ID fields are indexed automatically. Most other standard fields, such as Industry, Status, and CloseDate, are not indexed unless Salesforce has added an index for your org.
Filters that stop the index from being used
An indexed field does not help if the filter is written in a way the optimizer can't use. These patterns are common causes:
- A leading wildcard.
LIKE '%corp'cannot use an index.LIKE 'Acme%'can. - Negative operators.
!=,NOT IN,NOT LIKE, andEXCLUDESgenerally do not use an index. - A function wrapped around the field.
CALENDAR_YEAR(CreatedDate) = 2026is harder to optimize than a date range on the same field. - Comparing to null.
WHERE Field__c = nulloften can't use an index. - An OR with an unindexed field. Every condition in an OR needs to be indexed for the index to be used.
The date rewrite is the easiest to apply. Compare the field to a range using bind variables:
Datetime rangeStart = Datetime.newInstanceGmt(2026, 1, 1, 0, 0, 0);
Datetime rangeEnd = Datetime.newInstanceGmt(2027, 1, 1, 0, 0, 0);
List<Account> created2026 = [
SELECT Id, Name
FROM Account
WHERE CreatedDate >= :rangeStart AND CreatedDate < :rangeEnd
LIMIT 1000
];
System.debug('Accounts created in 2026: ' + created2026.size());The range keeps the raw indexed field on the left side of the comparison. The LIMIT caps the work if the range is wider than you expected.
Rewriting a negative filter
A negative filter can usually be turned into a positive one by listing the values you want. The positive form is only useful for selectivity if the field is indexed, so combine it with an indexed field when you can.
Datetime since = Datetime.now().addDays(-30);
// Hard to optimize: negative operator on a field that is not indexed
List<Case> a = [
SELECT Id FROM Case WHERE Status != 'Closed' LIMIT 200
];
// Better: positive values, plus an indexed date filter to narrow the rows
List<Case> b = [
SELECT Id
FROM Case
WHERE Status IN ('New', 'Working', 'Escalated')
AND CreatedDate >= :since
LIMIT 200
];The second query depends on a hard-coded list of statuses. If an admin adds a new open status, the list must be updated. That is the maintenance cost of this rewrite.
Reading the query plan
You don't have to guess whether a query is selective. The Developer Console has a Query Plan tool.
- Open Developer Console and choose Help > Preferences.
- Enable Enable Query Plan.
- Open the Query Editor tab, type a SOQL query, and click Query Plan.
The tool lists the plans the optimizer considered, with the cheapest first. Each row shows these columns:
- Leading Operation Type:
Indexmeans an index is used.TableScanmeans a full scan. - Cost: a relative number. A value below 1 means the query is selective. A value above 1 means it is not.
- Cardinality: the estimated number of rows the plan returns.
- sObject Cardinality: the total rows in the object.
- Fields: the indexed fields used by the plan.
Reduce the work a query does
Selectivity decides how rows are found. Other choices decide how much you pay after that.
- Select only the fields you use. Each extra field adds heap memory. Long text fields add the most.
- Add a LIMIT when you need only some rows. The 50,000-row limit is shared across all queries in the transaction.
- Use a SOQL for loop for large sets. Records are retrieved in batches, so you avoid holding the full list in the heap.
- Avoid querying inside loops. Collect Ids into a Set and query once with
IN. - Use
SELECT COUNT()to count rows. It returns an Integer without loading records. It still counts toward the query row limit.
Integer queriesBefore = Limits.getQueries();
Integer rowsBefore = Limits.getQueryRows();
List<Account> accts = [
SELECT Id, Name
FROM Account
WHERE Name LIKE 'Acme%'
LIMIT 200
];
System.debug(
'Queries used: ' + (Limits.getQueries() - queriesBefore)
+ ' of ' + Limits.getLimitQueries()
);
System.debug(
'Rows used: ' + (Limits.getQueryRows() - rowsBefore)
+ ' of ' + Limits.getLimitQueryRows()
);Run this in anonymous Apex and read the debug log. The Limits methods report consumption inside the current transaction, so you can use them to see which part of your code spends the most.
Common errors and how to respond
| Symptom | Likely cause | Fix |
|---|---|---|
| `Non-selective query against large object type` | Trigger query filters on unindexed fields, or a filter returns too many rows | Add an indexed filter, narrow the filter, or request a custom index |
| `Query is either selective or the query timed out` style failures in reports and list views | Table scan on a large object | Add a selective filter |
| Timeout after 120 seconds | Table scan, deep relationship queries, or very wide results | Narrow the filter and reduce fields |
| Fast in tests, slow in production | Test data is tiny | Use the Query Plan tool against realistic data |
| A formerly fast query slows down over time | Data growth moved the filter past the selectivity threshold | Re-check the plan and tighten the filter |
If a query cannot be made selective, move the work out of the synchronous path. Batch Apex processes records in chunks, and you can start it from a queueable job or a scheduled job. A batch can use a QueryLocator, which can return up to 50 million rows. Even there, a selective filter makes the job much faster.
Exercise
A trigger on Case runs [SELECT Id FROM Case WHERE Status != 'Closed'] and fails in production with a non-selective query error. Give two changes that could make the query selective, and say why each helps.
Show answer
First, replace the negative operator with a positive list, such as Status IN ('New', 'Working', 'Escalated'), because negative operators generally cannot use an index. Second, add a filter on an indexed field, such as CreatedDate >= :since, AccountId IN :accountIds, or OwnerId = :userId, so the filter returns less than the selectivity threshold. Status alone is probably not indexed, so the indexed filter is what makes the query selective. You can confirm the result with the Query Plan tool: the leading operation should be Index and the cost should be below 1.
Exercise
Why does WHERE CALENDAR_YEAR(CreatedDate) = 2026 cause trouble, and how do you rewrite it?
Show answer
A function wrapped around the field makes it harder for the optimizer to use the index on CreatedDate. Rewrite it as a range on the raw field: CreatedDate >= :rangeStart AND CreatedDate < :rangeEnd, where the two bind variables are Datetime values for 2026-01-01 and 2027-01-01.