I have the following three SOQL queries in a class that is being called by a Trigger. The Trigger counts the number of completed tasks and events for a given account.
List<Account> accounts = [SELECT ID, activity_count__c FROM Account WHERE ID IN :accountIds]; List<Task> compTasks = [SELECT ID, AccountID FROM Task WHERE Status = 'Completed' AND AccountID IN :accountIds AND CreatedById NOT IN :exclusions]; List<Event> events = [SELECT ID, AccountID FROM Event WHERE AccountID IN :accountIds AND CreatedById NOT IN :exclusions];
Periodically, I'm getting a 'caused by: System.QueryException: Non-selective query against large object type (more than 100000 rows)' error on the compTasks query. I've learned from our admin that this occurs when Leads are converted.
In searching for a solution I found a suggestion to add 'ORDER BY CreatedDate DESC LIMIT 10000' since CreatedDate is an index, and it will keep my search within the bounds of the large object limit.
Should I be concerned about limiting my query to 10000? Could I potentially be missing possible tasks to count? Or, is there a better way to make my count while avoiding the Non-selective query Exception?
group by AccountIdand count() in the select) would save you having to do any looping to get the counts per Account id.