I am trying to write a SOQL query that queries from Task the field LeadSource. In a report the name of the field that displays LeadSource is Contact/Lead. I have been trying different variations like

SELECT AccountId, Who.Name FROM Task
SELECT AccountId, Who.Lead FROM Task
SELECT AccountId, Lead FROM Task
SELECT AccountId, Who.LeadSource FROM Task

but so far unsuccessfully. Any hints appreciated.


If you have it the SOQL Polymorphism and Type OF feature enabled in your org, then you could use TYPEOF in your SQOL to try to get this info. Something like below

    WHEN Contact THEN Phone
    WHEN Lead THEN LeadSource
    ELSE Name

If it is not enabled, then I think you are forced to use a second query as related fields (who and What fields) are not accessible in a query for Task or Event. you would have to do a second query to get those. In that case, I would build a leadMap and a contactMap to hold the values you need.

map<Id,Contact> conMap = new map<Id,Contact>();
map<Id,Lead> leadMap = new map<Id,Lead>();
for(Task t : [Select Id, WhoId, Who.Type From Task Where YOUR CRITERIA]){
     if(t.Who.Type == 'Contact') {
         conMap.put(t.WhoId, null);
     } else {
         leadMap.put(t.WhoId, null);
conMap.putAll([Select Id, Name, Your_other_field_1__c, Your_other_field_2__c From Contact Where Id In : conMap.keyset()]);
leadMap.putAll([Select Id, Name, LeadSource, Your_other_field_1__c From Lead Where Id In : leadMap.keyset()]);

Now you have a map of contacts and leads that contains all related fields you might want access to.

For more info on SOQL Polymorphism and Type OF features see here http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_select_typeof.htm


Get the contact/lead ids :

SELECT AccountId, WhoId FROM Task

And with this WhoId you can now get the contacts or leads :

SELECT Id FROM Contact where Id = :WhoId
SELECT Id FROM Lead where Id = :WhoId
  • 1
    Thats a good workaround which I am trying to avoid and use a single query. – Koba Aug 12 '14 at 15:24
  • Ok, but I didn't see how doing with only one query ! – SF_user Aug 12 '14 at 15:26

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.