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

Getting a List of Contacts from a List of Accounts

sfdcfox helped me figure out how to get a list of accounts now I need to get a list of contacts from that list. I don't even have a code sample to kick this off because I can't figure out the best way to do it short of iterating through each account in the account list then building up a master list of its contacts. Does that sound like the approach to use or is there some kind of SOQL I can do against the accounts list I have?

Best Answer chosen by Admin (Salesforce Developers) 

Since contacts are linked to accounts, you can retrieve them all in the same query as the accounts by using the Child Relationship Name of the lookup field from a Contact to an Account, which is "Contacts":


List<Account> accsAndConts = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) From Account];


To then iterate through the resulting contacts you could do:

for(Account a : accsAndConts){
	for(Contact c : a.Contacts){
		//do stuff