0

I have a code like this -

//there i get all the Jaipur city employee list
List<Employee> employeeList = [select ID from Employee where city='Jaipur'];

Now i need to get Departments of these Employees. I do like -

List<ID> idsList = new List<ID>();

//Iterate employeeList to get employee IDS 
for(Employee emp : employeeList){
    idsList.add(emp.id);
}

// Then get Department List of these ids
List<Department> departmentList = [select ID, name from Department where empId IN: idsList];

I need to ask Is there any other way to get Departments? i mean i don't want to iterate over employeeList to form idsList and then use those ids in next query to get departmentList.

can't i get IDS list directly from employeeList without iterating it completely?

3
  • You could do Set<Id> idsList = new Map<Id,Employee>( [Select ...] ).keySet(); or I think you can even just use employeeList in place of :idsList in your query but you'd have to try that Commented Jul 29, 2013 at 8:09
  • will new Map<Id,Employee>( [Select ...] ).keySet(); throw any exception if [Select ...] returns 0 results ? Commented Jul 29, 2013 at 8:13
  • 1
    No, it will just be an empty set Commented Jul 29, 2013 at 8:21

2 Answers 2

4

I think u can use map instead of list like below

Map<id,Employee>  EmpMap = new Map<id,Employee>([select ID from Employee where city='Jaipur']);

and use this one in second query like

List<Department> departmentList = [select ID, name from Department where empId IN:EmpMap.keySet()];

Check below link for more details

http://developer.force.com/cookbook/recipe/initialising-maps-from-queries

0
3
List<Department> departmentList = [select ID, name from Department where empId IN (select ID from Employee where city='Jaipur')];

Here is other way of doing the same without iteration.

3
  • Yes i can do like this as well but i would not be able to use this ID list in following code if i go for it. Even you deserve 1 vote up Commented Jul 29, 2013 at 8:43
  • If you want to use this ID in other places then aggregation through map query as Venkatesh mentioned is nice approach.Thanks Commented Jul 29, 2013 at 9:05
  • Yes you are right mohith Commented Jul 29, 2013 at 10:01

You must log in to answer this question.

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