2

I want to get the IDs for all tasks...

I try:

List<String> ids = [SELECT ID FROM Task];

But that's give an illegal assignment error. I can't just assign from Tasks to Strings. So what is the short hand way to write this?

Thanks

0

2 Answers 2

16

This won't work, because the SOQL query will return a List<Task> regardless of the fields you query, however if you only need the ids, best thing you can do is make a map, then read the keyset, to get a set of Ids;

Map<Id, Task> taskMap = new Map<Id, Task>([SELECT Id FROM Task]);

now you have a set with ids you can use by doing:

Set<Id> taskIds = taskMap.keySet();
1
  • PJC's answer is correct. If you want a quick modification to your code; just use this: List<Task> ids = [SELECT ID FROM Task]; then you can iterate over them using: for(Task t: ids){ System.debug(t); }
    – Ashish
    Commented Mar 7, 2013 at 10:43
0

To get a list of strings you're going to have to loop over the results. Not super efficient but if you're not doing a whole lot else (seemingly the case since you only want one field) then you should be ok on limits:

List<String> ids = new List<String>();

for(Task t : [select Id from Task])
  ids.add(t.Id);

I suspect you might be just getting these to use in a sebsequent query, so you should be aware than you can do a subquery:

... where Task__c in (select Id from Task)
2
  • 1
    That's a huge waste of script statements (performance + spam in the debug log), shortcut via map is better;) And regarding the last bit - usually yes but for whatever reason Tasks & Events can't be used like that. SELECT Id FROM Account WHERE Id IN (SELECT AccountId FROM Task) will not even compile.
    – eyescream
    Commented Mar 7, 2013 at 11:40
  • Oh absolutely, hence I called it out and voted for the other answer myself ;)
    – Matt Lacey
    Commented Mar 7, 2013 at 11:42

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