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

dublintech
  • 4,253
  • 10
  • 40
  • 56

2 Answers2

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();
pjcarly
  • 7,451
  • 5
  • 36
  • 56
  • PJC's answer is correct. If you want a quick modification to your code; just use this: List ids = [SELECT ID FROM Task]; then you can iterate over them using: for(Task t: ids){ System.debug(t); } – Ashish Mar 07 '13 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)
Matt Lacey
  • 25,618
  • 7
  • 66
  • 149
  • 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 Mar 07 '13 at 11:40
  • Oh absolutely, hence I called it out and voted for the other answer myself ;) – Matt Lacey Mar 07 '13 at 11:42