Relationship Queries

Using relationship queries, we can retrieve the related objects data using the SOQL query.

Parent-to-child and child-to-parent relationships exist between many types of objects, for example, Account is a parent of
Contact.

Below diagram display relationship between Account and Contact.

To be able to traverse these relationships for standard objects, a relationship name is given to each relationship. The form of
the name is different, depending on the direction of the relationship:

child-to-parent relationship:

For child-to-parent relationships, the relationship name to the parent is the name of the foreign key, and there is a
relationshipName property that holds the reference to the parent object. For example, the Contact child object has a
child-to-parent relationship to the Account object, so the value of relationshipName in Contact is Account. These
relationships are traversed by specifying the parent using dot notation in the query, for example:

In the child to parent relationship, we can query on contact and retrieves the values from account that is associated.

Contact c = [Select First Name, Last Name, Account.Name, Account.Industry from contact where id = ‘XXXXXXXX’];

System.debug(‘Account Name: ‘ + c.Account.Name);

System.debug(‘Industry:  ‘ + c.Account.Industry);

Parent-to-child relationship:

For parent-to-child relationships, the parent object has a name for the child relationship that is unique to the parent, the
plural of the child object name. For example, Account has child relationships to Assets, Cases, and Contacts among other objects, and has a relationshipName for each, Assets, Cases, and Contacts.These relationships can be traversed only in the SELECT clause, using a nested SOQL query. For example:

In the parent -to-child relation, we can query on the parent object and we will get details about child record.

Account a = [Select Name, (Select Contact.FirstName, Contact.LastName from Account.Contacts) from account where id = ‘XXXX’];
System.debug(‘Name:’+ a.name );