Hi All
Let’s discuss the Non-selective query exception in Salesforce.
Q. When does this error occur?
Ans. This error occurred if you are running a SOQL query for an object which has more than 2 LAC (200,000) records. (If you are running a query inside a trigger). If you try running this query inside any controller or developer console, you will not face any error.
Q. What is the easiest way to fix it?
Ans.Most of fields in where clause should be index field. On every object there are few standard fields which are indexed by default. Below are the given fields.
-
Id
-
Name
-
RecordType
-
Createddate
-
Lookup/Masterdetail
-
OwnerId
-
Systemmodstamp
-
Unique field (Any field which is marked as unique)
-
External field ( Custom field which is marked as external field)
If none of your field from where clause are indexed field, try making most suitable field as external field.
Q. Already contains indexed field, but still getting Non Selective query exception?
If fields in where clause has null in there values in query, then query become non selective. Doesn’t matter fields are indexed or non indexed.
eg. We are executing below query.
select id, name from Book__c where title in : setOfTitle
and for whatever reason if null was added in setOfTitle, query will becom non selective and start giving error.
Apart form it take care of following scenarios in SOQL query,if any of these is part of your query , it will cause the same issue.
SOQL filter conditions with
-
!=
-
NOT LIKE
-
EXCLUDES
-
comparison on text fields eg. TEXT_FIELD <=, TEXT_FIELD >= etc.
-
LIKE %STRING%
Thanks for reading. Hope you find it useful.
Kindly like, comment,share if you find it useful.