Parent-child and Child-Parent SOQL in Salesforce Apex

Parent-Child SOQL: 

In order to fetch child object data while querying on parent object, we need to write subquery as illustrated below:

Scenario: Suppose we have two objects:

  • Student(Api Name: Student__c)
  • Student Address(Api Name: Student_Address__c)
Student is parent object and Student Address is child object.

SOQL: In order to fetch child object data with parent object using parent-child query, first we need to check for "Child Relationship Name" on child object and use it in subquery.
For above mentioned scenario, "Child Relationship Name" on Student Address is "Student_Addresses". As Student Address is a custom object therefore we will use "__r" with it's "Child Relationship Name" in sub query. So the SOQL will be as below:

Select Name, (Select Id from Student_Addresses__r) from Student__c;

If child object is a standard object then we need not to use "__r" with "Child Relationship Name" in sub query. We just need to use "Child Relationship Name" (without "__r") in subquery and SOQL will be as below:


Select Id, Name, (Select Id, LastName from Contacts) from Account;

Note: In above SOQL, Contacts is "Child Relationship Name" on child object i.e. "Contact" object.

Child-Parent SOQL:

In order to fetch data from parent object while querying on child object,  we need not to write sub query. We can access parent object's fields using dot operator with the name of the foreign key field. If parent object is custom object then we need to use "__r" with foreign key field.

Note: For child-to-parent relationships, the relationship name to the parent is the name of the foreign key.

Standard object:

Select Id, LastName, Account.Name from Contact;

Custom object: We need to use "__r" with foreign key field as illustrate in below SOQL:

Select Id, Student__r.Name from Student_Address__c;



 

Comments

Popular posts from this blog

Difference between var, let and const keyword in JavaScript

Salesforce Record Id

Salesforce External ID