Skip to content

Non-selective query against large object type (more than 200000 rows)

The error names its own two usual causes: a null in your bind list, or skew. How to find which one you have and fix a trigger query that worked until last week.

TL;DR

  • This System.QueryException fires when a SOQL query in a trigger runs against an object holding more than 200,000 rows and the optimiser cannot use an index for any of its filters.
  • The full error message lists its own two most common causes, and they are the right place to start: a null in the bind variable, and data skew on the value you filter by.
  • The null case is the one that looks like a mystery. A trigger builds Set<Id> from a lookup field on Trigger.new, one record has the lookup blank, and an otherwise selective query stops using its index.
  • The row count includes soft-deleted records in the Recycle Bin, so an object can cross the 200,000 mark without anyone noticing a jump in live data.
  • Fix the filter first (strip nulls, anchor on ids, add an indexed condition), check it with the Query Plan tool, and ask Salesforce Support for a custom index only once the filter could use one.

What You'll Learn

  • What the full error message is telling you, line by line
  • Why a single blank lookup can make a selective query non-selective
  • How skew defeats an index that exists and is correctly defined
  • How to confirm the fix with the Query Plan tool before deploying
  • When a custom index is the answer, and when it changes nothing

The Problem

The full message is longer than the part that appears in most logs:

System.QueryException: Non-selective query against large object type (more than 200000 rows).
Consider an indexed filter or contact salesforce.com about custom indexing.
Even if a field is indexed a filter might still not be selective when:
1. The filter value includes null (for instance binding with a list that contains null)
2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)

It arrives in a trigger that has worked for years. Nobody changed the query. Either the object grew past the size where Salesforce stops tolerating a full scan inside a trigger, or a record came through with a value the query had never seen before, usually a blank one.

The general theory of selectivity thresholds is covered in Large Data Volumes: When a Query Stops Being Selective. This post is about the error itself, and about the two causes the message names, because they explain most of the tickets.

Common questions this article answers:

  • The field I filter on is indexed, so why is my query non-selective?
  • Why did this start failing when nobody deployed anything?
  • Will a custom index from Salesforce Support fix it?

Quick Answer

Salesforce throws this exception when a SOQL query running in a trigger targets an object with more than 200,000 rows, counting soft-deleted rows in the Recycle Bin, and none of its filters can use an index. Check the two causes the message lists. First, look for a null in the bind variable: a trigger that collects lookup values from Trigger.new into a Set and queries WHERE Field__c IN :values picks up a null whenever a record has the lookup blank, and an index cannot be used for a null value by default. Remove nulls before the query. Second, look for skew: if the value you filter on matches more than the index threshold, which for a custom index is 10 percent of the first million rows and 5 percent beyond that, the index is ignored. Anchor the query on something narrower, such as the trigger's own record ids, or add a second indexed filter. Confirm the change in the Query Plan tool, where a cost below 1 means an index will be used. Ask Salesforce Support for a custom index only when the filter is genuinely selective and simply has no index.

If you have the error in front of you, the picker below works through the same checks in order and ends at the fix. The sections after it explain each cause.

Got the non-selective query error in a trigger? Answer about the failing query; the path you take stays open.

Is the filter an IN or = bind built from Trigger.new, such as the values of a lookup field?

The message names two causes

Check the bind first, then the value, then the shape of the filter. The panel gives the cause and the fix.

Cause 1: a null in the bind variable

This is the most common cause and the least obvious, because the query looks fine and passes in every test.

// Looks selective. Is not, if any Case has a blank Asset__c.
Set<Id> assetIds = new Set<Id>();
for (Case c : Trigger.new) {
    assetIds.add(c.Asset__c);
}
List<Case> related = [
    SELECT Id, Status FROM Case WHERE Asset__c IN :assetIds
];

Asset__c is a lookup, and lookups are indexed. With a handful of asset ids the query is selective. The moment one case in the batch arrives without an asset, assetIds contains null, and the query is now also asking for every case where Asset__c is blank.

Two things go wrong at once. By default, Salesforce's index tables do not include rows where the field is empty, so an index cannot help find them. And on most objects, "every row where this lookup is blank" is a large share of the table. The optimiser has to scan, the object is over 200,000 rows, and the trigger throws.

The fix is one line:

assetIds.remove(null);
if (assetIds.isEmpty()) return;

Or guard at collection time with if (c.Asset__c != null). The early return matters as well: an empty IN list is cheap, but skipping the query entirely is cheaper and keeps the trigger out of the SOQL budget.

This cause explains the "nobody changed anything" reports. The code was always vulnerable. It failed the first time a record with a blank lookup arrived in a trigger batch on an object large enough to be enforced, which is often a data load or an integration that the UI never exercised.

Cause 2: skew on the value you filter by

The second cause is about data shape. An index exists and the filter value is not null, but that value matches too many rows.

// Selective for most accounts. Not for the one with 400,000 cases.
List<Case> open = [
    SELECT Id FROM Case WHERE AccountId IN :accountIds AND IsClosed = false
];

AccountId is indexed. For a typical account, it matches a few hundred cases and the query is fast. For a catch-all account that holds a large share of all cases, the same filter exceeds the threshold and the optimiser ignores the index. The query is selective or not depending on which records are in the trigger batch.

The large data volumes post covers the thresholds in full. In short, a standard index is used when the filter matches under 30 percent of the first million rows and 15 percent beyond, and a custom index under 10 percent and 5 percent, capped at 333,333 rows. On an object of 3 million records, a custom-indexed value shared by 250,000 of them is over the line.

Skew is usually a data problem with a code symptom. The catch-all parent (the "Unknown" account, the integration's default owner, the "Unassigned" queue) is the same pattern behind UNABLE_TO_LOCK_ROW. Two fixes help:

  • Add a filter that narrows within the skewed value. A date range on an indexed field such as CreatedDate, or a record type, can bring the matching set back under the threshold. When several filters are combined with AND, the optimiser can use an index as long as that filter on its own matches no more than 20 percent of the object.
  • Spread the skewed value. Splitting a catch-all parent into several, or giving unmatched records no parent at all, removes the cause in every query and in every lock.

Anchor trigger queries on the trigger's own ids

Many trigger queries that hit this error are asking a broader question than they need to. A trigger on Case usually wants information about the cases in the batch, or about their immediate parents. Both are reachable by Id, and an Id filter over 200 values is about as selective as SOQL gets.

// Broad: every open case on these accounts
[SELECT Id FROM Case WHERE AccountId IN :accountIds AND IsClosed = false]

// Narrow: just the accounts, and whether each has an open case
[SELECT Id, (SELECT Id FROM Cases WHERE IsClosed = false LIMIT 1)
 FROM Account WHERE Id IN :accountIds]

The second form queries Account by Id, which is selective for a trigger-sized list, and pulls the related cases through a subquery. Whether this works depends on what the trigger needs, but asking what the trigger needs to know about these records often removes the large-object query entirely.

Check the plan before you deploy

The Query Plan tool in the Developer Console shows how the optimiser would run a query today. Enable it under Help, then Preferences, then "Enable Query Plan", paste the query with literal values in place of bind variables, and read the plans it offers.

The column that matters is Cost. A plan with a cost below 1 is selective and will be used. If every plan costs more than 1, the query will scan, and inside a trigger on a large object it will throw.

Run it with the values that cause trouble: a null, the skewed parent, the busiest owner. A query plan built for a typical value will look selective and tell you nothing about the batch that fails.

When a custom index helps

A custom index is the right fix when the filter is genuinely narrow and the field simply is not indexed. Fields marked External ID or Unique are indexed automatically. For other fields, Salesforce Support can create a custom index on request, and for fields that need nulls included, Support can build an index that covers empty values as well.

It does not help when the filter is the problem:

  • Negative operators. !=, NOT IN, NOT LIKE and comparisons with an empty string do not use custom indexes.
  • Leading wildcards and CONTAINS. A leading wildcard cannot use an index at all, and CONTAINS scans the whole index, which Salesforce treats as non-selective past 333,333 rows.
  • Values over the threshold. An index on a field where the filter value matches 40 percent of rows will be ignored every time.
  • Non-deterministic formula fields, which cannot be indexed at all.

Index requests have a lead time, so raise them before the object is near the limit, not during the incident.

Count the Recycle Bin

Soft-deleted records still count toward the object's size for selectivity purposes. An object with 180,000 live rows and 30,000 in the Recycle Bin is over 200,000. Bulk deletes followed by reloads, a common pattern in nightly integrations, can push an object over the limit for up to 15 days while the deleted rows wait to be purged.

Hard delete through the Bulk API, or emptying the Recycle Bin after a large purge, keeps the count honest. Do not rely on it as the fix, though. An object that is close to 200,000 today will cross it on its own soon enough.

Frequently Asked Questions

Q: Why only in triggers?

A: Salesforce enforces the error on queries that run in a trigger against a large object, because a scan there holds up every save on the object. The same query from an anonymous Apex window or a Batch start method may run slowly instead of failing. That makes it worth fixing everywhere, but it only throws in trigger context.

Q: The field I filter on is a lookup, so it is indexed. Why is the query non-selective?

A: Either the bind contains a null, which the default index does not cover, or the specific value is shared by too many rows. The error text lists both for that reason. Check the bind set first; it takes a minute and it is the cause most of the time.

Q: Can I raise the 200,000 row threshold?

A: No. It is a platform rule. The way out is a query that can use an index, which is in your control.

Q: Will LIMIT 1 make the query selective?

A: No. The optimiser decides how to find the rows before applying the limit, so a non-selective filter with LIMIT 1 still scans.

Q: Why did it pass in the full sandbox?

A: Full sandboxes copy data but not always the same distribution of blanks and catch-all values, and test data built by a factory rarely includes a record with the lookup left blank. Add one deliberately to the trigger's test class.

Key Takeaways

  • The error fires on non-selective trigger queries against objects over 200,000 rows, including soft-deleted rows.
  • Read the whole message. Nulls in the bind and data skew cover most cases.
  • Remove nulls from every bind set built from Trigger.new, and return early when the set is empty.
  • Skew is a data problem. Narrow the filter or spread the catch-all value.
  • Anchor trigger queries on Id where the logic allows it.
  • Test with the Query Plan tool using the values that fail, and request a custom index only for a filter that is narrow enough to use one.

What's Next?

Recommended Reading:

Action Items:

  1. Search your triggers for IN : binds built from Trigger.new and add a remove(null) before each query.
  2. In Anonymous Apex, run [SELECT COUNT() FROM Case ALL ROWS] and [SELECT COUNT() FROM Case WHERE IsDeleted = true ALL ROWS] for each of your largest objects to see how close they are to 200,000, Recycle Bin included.
  3. Find the catch-all parents: group child records by their parent lookup and look at the top ten.

Resources & References

Responses

Checking your session.

Loading responses.