-1

I have creates a List of contacts in Salesforce UI and also created related tasks such as activity logs on those contact. Now I want to know how to fetch all the tasks related to those contacts. I have tried the following using execute anonymous in developer console:

List<Contact> conList  = [SELECT Id From Contact limit 5];
System.debug('--Task details with id ---' + conList);

But this doesn't show me the task objects, Please help me out on finding how to query out those tasks and their fields in apex code.

1
  • Please explain to me your action on rolling back my edits and therefore taking my rightfully earned credits away, I don't see a benefit in your action since you're literally using my edits, and my edits certainly addressed the original issue with this ticket which was the need of details and clarity, the history of my changes and your rollback shows that you didn't add anything to justify the rollback (you've simply changed list to List and a couple more of these case changes just to be able to submit) and when I reported this to SO they said "we can't do anything about rollbacks" Thank you!
    – Bahman.A
    Commented Apr 10, 2020 at 23:15

2 Answers 2

6

You will need to SOQL Contact first then feed the Tasks List with those ContactIds to get the related Tasks.

Contact SOQL

Contact[] cons = [SELECT id from Contact ];

Now, feed these ContactIDs to get related Tasks

Tasks

Task[] conTasks = [SELECT id, subject FROM Task WHERE Whoid in: cons];
System.debug('tasks:' + conTasks);
3
  • Only problem with this one is it requires two queries and it retrieves all Contacts from database. Outer join is much optimal for such requirements.
    – Raul
    Commented Feb 20, 2017 at 8:15
  • Agreed, however, this was to explain OP in simplest way and how to take things forward.
    – Mahmood
    Commented Feb 20, 2017 at 8:19
  • Agree with your approach! :)
    – Raul
    Commented Feb 20, 2017 at 8:38
3

Additionally you can also use inner or outer join in SOQL to get Tasks based on Contact.

Outer join SOQL example:

SELECT Id, Subject FROM Task WHERE 
    WhoId IN (SELECT Id FROM Contact)

Inner join SOQL example:

for(Contact objContact: [SELECT Id, LastName, 
    (SELECT Id, Subject FROM Tasks) 
    FROM Contact]) {

    // Access Contacts through objContact
    for(Task objTask: objContact.Tasks) {
        // Access Tasks through objTask
    }
}
1
  • +1 for the outer join example. I would have included this in my answer, but now it makes little sense since there is your answer with this detail. :)
    – Mahmood
    Commented Feb 20, 2017 at 8:22

Not the answer you're looking for? Browse other questions tagged .