5

I need to access the fields from the nested Select statement. Here is the code

Select Name, id, (SELECT id FROM Account.Contacts)
       from Account where id = '0011a000004eVlYAAU' 

How do I access the "id" from "Account.Contacts". I found an answer but I am not able to make it work.

For(string b : [Select Name, id, (SELECT id FROM Account.Contacts)
       from Account where id = '0011a000004eVlYAAU'])
        {

            system.debug(b.Account.Contacts);
        }

1 Answer 1

4

Inner query always return list of child records. So for each record retrieved by the outer query, a list of child records are available through the inner query.

To access the records returned by the inner query, you can assign them to a list and iterate over it.

for(Account acc : [Select Name, id, (SELECT id FROM Account.Contacts) from Account]){
    List<Contact> lstContact = acc.Contacts;
    for(Contact con : lstContact){
        System.debug(con.Id);
    }
}

Hope it helps.

1
  • Thanks Vigneshwaran that was an incredibly fast response I will try that and let you know if it worked! Commented Apr 16, 2016 at 14:08

You must log in to answer this question.

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