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
Sarah OrensSarah Orens 

SOQL Parent Accounts and all Contacts that roll up to the Parent Account

Let's assume that I know very little (if anything) about querying data in salesforce, or writing any type of query for that matter. 

I've been tasked with finding all contacts that roll up to a Parent Account. Is this possible? It seems so simple but after researching I'm running into some trouble with writing a query that involves a relationship. 

Thanks for any insight that you might be able to provide! 
Akhilesh Reddy BaddigamAkhilesh Reddy Baddigam
Account[] acctsWithContacts = [SELECT Name, (SELECT FirstName,LastName FROM Contacts) FROM Account WHERE Name = 'SFDC Computing'];

 // Get child records Contact[] cts = acctsWithContacts[0].Contacts; 
System.debug('Name of first associated contact:'+ cts[0].FirstName + ', '+cts[0].LastName);


You can go through this link in trailhead to understand (https://trailhead.salesforce.com/en/modules/apex_database/units/apex_database_soql) how SOQL works in salesforce
HARSHIL U PARIKHHARSHIL U PARIKH
In salesforce you can write query two ways
1) Parent to Child
2) Child to Parent

Scenario:
Let's say you have 10 Accounts in your salesforce and each of them have 5 contacts attached to it. Now you want to query all the Accounts with its associated contact Information

Solution: 1) Parent to child
List<Account> gettingAllAccountsWithContacts = [Select Id, Name, (Select Id, FirstName, LastName FROM Contacts) FROM Account];
above select statement returns multiple records correct..(10) thats why we need to store them into the List. And the retrieve type for the records is Account records so we will have List<Account>. If the retrieve type of the records are Opportunity records then we would had List<Opportunity>

Solution; 2) Child to Parent
List<Contact> contactRecordsWithTheirAccountInfos = [Select Id, FirstName, LastName, Account.Name FROM Contact];
In salesforce if you want to fetch parent object info from child then you need to use DOT notation means you need to write ParentObjectName.FieldName
In our query above the return type of records is contacts thats why we have List<Contact>
So, basically the second query would contain all the contacts in the org (up to 50,000) but in our case 50.

Remember one SOQL (Salesforce Object Query Language) can fetch up to 50,000 records in one query.

Hope this helps and if it solves your question then please mark it best answer since it will help other people to understand more about SOQL!
Thank You.