[SalesForce] SOQL: Execute Anonymous and Query Editor returning different results

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'
 LIMIT 1

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];
system.debug(d);

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?

Thanks!

Best Answer

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.

Related Topic