I'm trying to query Task from Lead. In the developer console > query editor, I have the following SOQL query:

 SELECT name, (SELECT id, subject, description FROM Tasks)
 FROM Lead
 WHERE id = '00JQ0000005h0FfQPP'

This returns

Name: Robby

Robson Tasks: [{"Id":"00JT000000YzDA9NNP","Subject":"Call","Description":"Had a call with Robbie. Need to follow up in a week."}]

But when I execute the following in the anonymous window:

lead d = [SELECT name, (SELECT id, subject, description FROM Tasks)
          FROM Lead
          WHERE id = '00JQ0000005h0FfQPP'
          LIMIT 1];

I just get:

|USER_DEBUG|[10]|DEBUG|Lead:{Name=Robby Robson, Id=00JQ0000005h0FfQPP}

The purpose of the script is to fetch the description from the latest task associated with the lead. Originally I thought I could just do this:

string lastNote = [SELECT (SELECT description FROM Tasks Order By CreatedDate Limit 1)
                   FROM Lead
                   WHERE id = :upsertedLeads[i].getId()
                   LIMIT 1].tasks[0].description;

But that returns an index out of bounds, due to tasks[0].

How should I proceed?


2 Answers 2


System.debug(d) is the issue because d has been defined as a lead record. If you want the task, than debug that. It's not that your query isn't working, you just aren't debugging more than the lead record.

But, I agree that you should just query task directly.


You can directly query the Task object using the Lead Id and use the description without doing the parent child subquery.

Task recentLeadTask = [Select Id, Description From Task Where WhoId = :YourLeadId Order By CreatedDate Limit 1];  
if(recentLeadTask != null)  
    String taskDescription = recentLeadTask.Description; 

looking at your last part of code, it seems you are running this query inside a loop which is not generally not recommended since it will hit the governor limits..

if that's the case consider moving the query out of the loop.

  • Good call regarding the loop. It's a bad habit of mine. Your method totally works - but why isn't mine working as well?
    – ZAR
    Commented Aug 4, 2015 at 14:49

You must log in to answer this question.

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