Loading

Non-Selective Query Error 'System.QueryException' in Salesforce Apex Trigger But Succeeds as Standalone Query

게시 일자: Jun 12, 2025
상세 설명

Apex code may receive a "System.QueryException: Non-selective query against large object type" error when attempting to run a SOQL query via an Apex trigger context. The full error is as follows:

"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)


However, the same query runs successfully when run via the Developer Console (i.e. anonymous Apex). Why does it not error out in this case too?

솔루션

By design, non-selective queries on large object types are not allowed on trigger context (when evaluating Apex triggers). This design restriction prevents the impact a non-deterministic query execution time (due to a full/partial table scan required to perform the SOQL query) could have on the end-user's experience. As a result, attempts to run a non-selective query on a large object type within a trigger context will be prevented, and the‌ error message will be displayed.

NOTE: If this restriction wasn't in place, and the affected query was run within a given trigger that gets invoked upon saving a record, in a worst case scenario, the end user would need to wait for the query to time out to get some UI feedback.

The same restriction does not apply when the query is run within the Developer Console or via the SOAP/REST API. In this case, a standard query timeout will apply. In other words, the query will be attempted, and will be timed out only if it takes longer than a certain time.

It is suggested that the affected SOQL query be optimized so that it can leverage an index. See Salesforce query search optimization developer cheatsheet for more details on how to optimize a SOQL query.

Knowledge 기사 번호

000386468

 
로드 중
Salesforce Help | Article