6

Child to Parent Relationship

What Is SOQL Relationship Queries?

Relationship queries involve at least two objects, a parent and a child. These queries are used to fetch data either from the Parent object when the SOQL query is written on the child, or from the child object when the SOQL query is written on the parent.

What Is Child To Parent Query In Salesforce?

A child-to-parent query in Salesforce is used to retrieve data from a child object while accessing fields from its related parent object using relationship notation.

 For example, Whenever we need to fetch data from parent object fields that contain child records, we use a child to parent relationship in Salesforce.

For Standard Objects

SELECT Field_Name, RelationshipName.Parent_Obj_Field FROM Child_Object; List < Opportunity > oppList = [SELECT Name, Amount, CloseDate, Account.Name FROM Opportunity ]; for (Opportunity o: oppList) { System.debug('Opp: ' + o.Name + ' Acc: ' + o.Account.Name); }

For Custom Objects

SELECT(Field_Name), RelationshipField__r.Parent_Obj_Field FROM child_object; List < Branch__c > branchList = [SELECT Branch_ID__c, State__c, Branch_of_Bank__r.Bank_Name__c from Branch__c ]; for (Branch__c bl: branchList) { System.debug('Bank Name: ' + bl.Branch_of_Bank__r.Bank_Name__c + ',Branch: ' + bl.State__c); }
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Frequently Asked Questions

How do you write a child-to-parent query in SOQL?

To write child-to-parent queries in SOQL, you use the child object and dot notation to traverse to the parent.

What is dot notation in SOQL?

Dot notation in SOQL is used to move object relationships. In standard relationships, you use ParentObject.Field and in custom relationships, RelationshipField__r.Field__c is used.

Can we access multiple levels in a child-to-parent query?

In SOQL, you get access to 5 levels of child-to-parent queries. Going beyond 5 levels is not allowed and can cause errors.

Why do we use the child-to-parent relationship?

We use this child-to-parent relationship to retrieve the parent object field data for a child record in a single query.

Book Free15-Minutes Career Counselling