function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SrtSrt 

How to retrieve fields from Sub query in Apex code ??

 list<Account> ACC = [select id,  (select ID, Name from Contacts) from Account];

From the above statement how to retrive and assign contact name to a Apex variable?
 
VamsiVamsi
Hi,

Use the below one 
 
for(Account an : ACC)
​{
  for(Contact cn : an.Contacts)
{
    string name = cn.Name;   
}
}

Hope this helps 

Please mark as best answer if the above helps ...!!
Marcelo CostaMarcelo Costa
Hi Srihari!
In your example, You are querying for all the Accounts and their Contact list.
Besides my OCD that tells me that variables name should be allways lowercase, ;) the way you can retrieve the contact list for a acoount is as follows:
List<Contact> contactList = ACC.get(0).Contacts;
What the above code does is: it assumes you have at least one Account and the first account has contanacts. (Just following your example).
The List contactList will have all the contacts for the first retrieved Account. from there, you can iterate through the list and do whatever to the contactList.get(i).Name;

Good Luck :)
 
Heidi ApaHeidi Apa
Hi Srihari!

If you want all the contact names of all the accounts you cant save it in just one variable, you can create a list of contacts or a map of account and its related contacts..
list<Account> ACC = [select id,  (select ID, Name from Contacts) from Account];
Map<Id, List<Contact>> contMap = new Map<Id, List<Contact>>();
List<Contact> contList;
for(Account a : ACC)
{
    contList = new List<Contact>();
    
    for(Contact c : a.Contacts)
    {
        contList.add(c);
    }
    contMap.put(a.Id, contList);  
}
System.debug(contMap);
I hope it helps! :)
 
genuine cerificategenuine cerificate
Get 100% Registered IELTS,TOEFL,ESOL CERTIFICATES WITHOUT EXAM PASSPORTS,IDS(Whatsap: (+27)83 880 8170) 
 
Suraj TripathiSuraj Tripathi
Hi Srihari
Please try this piece of code .
 
public class AccContactSub {
    public static void text(){
        list<Account> ACC = [select id,  (select ID, Name from Contacts) from Account limit 100];
        list<Contact> ContactList = new List<Contact>(); 
        for(Account a : ACC)
        {
           for(Contact c : a.Contacts)
            {
               ContactList.add(c);     //  assign contact to the list
            }
        }
    System.debug(contactList);
    } 
}

Hope it's help you.

Regard
Suraj
SrtSrt
Hi All,

Thanks very much for helping out.