0

I am building a trigger on the Account object to calculate various task rollups (Completed Calls, Completed Emails, Open Tasks, etc..), and I am trying to make it also account for tasks that are related to Opportunities and Contacts that are in turn related to the Account in question.

So as part of the trigger logic, I am querying all child Contacts and Opportunities of all the Accounts in Trigger.new. Here is my code:

Set<ID> idsInTrigger = new Set<Id>();

for (Account a : Trigger.new) idsInTrigger.add(a.ID);

List<Task> allChildTasks = [SELECT ID, OwnerId, What.Id, What.Type, Who.Id, IsClosed, ActivityDate, Type FROM Task WHERE What.Type = 'Account' AND What.Id IN :idsInTrigger];

List<Contact> allChildContacts = [SELECT ID, Account.Id FROM Contact WHERE Account.Id IN :idsInTrigger];
List<Opportunity> allChildOpportunities = [SELECT ID, Account.Id FROM Opportunity WHERE Account.Id IN :idsInTrigger];

I am now running into a "Non-selective query" error on the last two queries. I was under the impression that since Account is a Lookup field (and so should be an indexed field), and since no account has more than a few hundred contacts at the very most (and many fewer opportunities), this query would be fine. Why am I getting this error?

1

You are getting error because the foreign key field in contact & opportunity pointing to row id of account is accountid and not account.id. So the queries should be

List<Contact> allChildContacts = [SELECT AccountId FROM Contact WHERE AccountId IN :idsInTrigger];
List<Opportunity> allChildOpportunities = [SELECT AccountId FROM Opportunity WHERE AccountId IN :idsInTrigger];

Also there is no need of specifying id field in soql queries it is automatically(implicitly) retrieved everytime

  • Thanks, this worked. That was actually how the queries were originally written; I first had the non-selective query error on the first query (of Tasks) - I added the What.Type filter to solve that, and for some reason this inspired me to put the dot notation in my other What and Who field references... fixed one line and broke the others. – OBerm Feb 19 '15 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.