Non-selective query against large object type in Salesforce

Posted on 19-04-2013 10:35 by graham
When performing a SOQL query in Salesforce, you might encounter the following exception:
Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or contact 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)

The error is caused by running a query against an object type that contains a lot (more than 100,000 records). However, you might be surprised that when you try to reproduce it in an Apex class, it does not appear. The reason is that this exception is thrown only in Apex triggers.

Avoiding the Non-selective query exception

To avoid the exception, make sure:
- You run your query against an indexed property. To make a property indexed, make it an external ID.
- If you are using a set of IDs in the query, make sure the set does not contain null values. E.g.
Potential non-selective query example
List<Id> ids = new List<Id>();

// ids list contains a null value, which might cause a non-selective query exception
List<Case> cases = [SELECT Id FROM Case WHERE Id IN :ids];

- If you still get the error, trying restricting the query criteria by putting a condition on some other propery, e.g. LastModifiedDate, CreatedDate etc.


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems