I am trying to get the latest task created on Lead from task object.

My scenario is that if there are 2 leads - Lead1 and Lead2. And both have 2 task created for it, Lead1 contain taska - (created date = today) taskb - (created date = yesterday). And for Lead2 contain taskc - (created date = today - 2) taskd - (created date = today - 4).

It should give result of all the latest created task in the lead1 and lead2 (Result - lead1 (taska) And Lead2(taskc)).

Please provide me the possible ways to do this scenario.


You could use a subquery in this case. This query will fetch all the tasks for the lead. you wil have to order the results by Created Date and then limit it to 1.

List<Task> latestTasks = new List<Task>();
for(Lead ld : [Select Id, Name,
    (Select Id, Subject from Tasks Order by CreatedDate DESC Limit 1) 
    from Lead]){

    latestTasks.addAll(ld.Tasks); // will add 0 if subquery is empty or at most 1 because of LIMIT in the query
  • I believe he wants to get Latest Tasks per lead, thats why i had added the List of leads and added the leads into the list. This way he would have the lead as well as the Task associated with the lead. Or may be use a Map<Id, Tasks> which will store the key as Lead Id and value as Task. Jan 30 '13 at 7:59
  • But if he needs both, he can simply store the results of query in a List<Lead>, you don't need a for loop and it will contain tasks too ;) The less code the beter.
    – eyescream
    Jan 30 '13 at 8:01

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.