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
Ashritha ReddyAshritha Reddy 

how can we do query child from parent and parent from child?

how can we do query child from parent and parent from child?
Vasani ParthVasani Parth
Ashritha,

Lets say, you want to find out what is the name of our Accounts and which user owns them
Child to Parent
SELECT Name, Owner.Name FROM Account
 Here we are at the child querying the parent so we use the relationship field ‘owner’ then we get the field ‘name’. We can say Owner.Name because for each Account record there will be at most one owner with one name. You can think of the relationship field as kind of like a pointer to the related object. We can then use that pointer to access the fields of the related object. It’s the “many” looking at the “one” that allows us to use the previous syntax

What if we wanted to change direction and thus change the cardinality? In this query we answer the question “Who are the contacts for each Account?”
Parent to Child
SELECT Account.Name,(SELECT Contact.Name FROM contacts) FROM Account
You woll notice how the SOQL syntax has changed. Since there are now zero or more possible Contacts for each Account we can no longer use the relationship field to point to a single Account like we could for Owner in our first query. We need to use a nested select to build a result set that contains all the related Contacts. For each Account we match all the related Contacts with this syntax. There’s a couple other things worth noting. First, we are using the relationship name ‘contacts’ to refer to related child records. Second, I prefaced each “name” field in the query with Account and Contact. This isn’t necessary but a best practice to remove ambiguity when reading the statement.

Please mark this as the best answer if this helps
 
sachin sabusachin sabu
Refer this link
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_using.htm
S Hemanth KumarS Hemanth Kumar

for(Contact objContact: [SELECT Id, LastName, AccountId, Account.Name FROM Contact]) {
 system.debug('====Account Name======'+objContact.Account.Name);

}