4

I have the following query that works for getting all the Tasks and Events for a Lead.

[SELECT ID, activity_count__c, 
(SELECT ID FROM Tasks WHERE Status = 'Completed'), 
(SELECT ID FROM Events) FROM Lead WHERE ID IN :leadIds];

I tried to convert it to get all the Tasks and Events for an Account, like so:

[SELECT ID, activity_count__c, 
(SELECT ID FROM Tasks WHERE Status = 'Completed'), 
(SELECT ID FROM Events) 
FROM Account WHERE ID IN :accountIds];

However, the result was that I only received the Events and Tasks made on the account directly, and not on the objects associated with the account, such as Opportunities, Contacts, Cases, etc.

Is there a way to get all the data from the Account and its associated objects in a single SOQL query? Or, do I need to query each of the associated objects and parse each set of results separately?

3

The short answer is not easily, or at least not with a single query like you're showing above. If the WhatId is not associated directly with the account, you would need to query all related objects to the account, then the associated tasks. If this is in a trigger, making it bulk safe is going to involve a couple of maps.

|improve this answer|||||
  • 1
    Just to clarify here, the strategy would be to obtain all the ids of Account, Contact etc first (perhaps querying into maps in case fields of the objects are needed), and then do a single query of each of the Tasks and Events using those ids to match the WhatId (and WhoId) fields right? – Keith C Mar 28 '14 at 15:38
  • 2
    That's correct, the strategy would be to build list of ids of records that you care about associated with the account--contact ids, case ids, etc. Then you could query for for the Activities whose WhatId are in that set of ids. – greenstork Mar 28 '14 at 15:40

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.