SalesforceBlue

Feel the rhythm of Salesforce

Apex

Apex SOQL Relationship Queries Simplified

Apex SOQL Relationship Queries allows us to query the related objects’ records from the same query. It is not similar to the SQL joins and we have to create relationships between objects in order to allow relationship queries.

Query Parent Records From Child

Let’s say we have created a custom object Region__c which is a look up on Contact.

Now we will query the Region__c Name field from Contact which is as follows :

// Query Parent Record From Child
List<Contact> contactList = [SELECT Id, Region__r.Name FROM Contact LIMIT 100];

// Iterating On The Returned List
for(Contact con : contactList) {
    System.debug('Region Name ' + con.Region__r.Name);
}

Here in the above code block, we are fetching the Parent Object Region__c Name by referring to the parent relationship Region__r.

We can query any fields on the parent Region__c field by referring the parent relationship Region__r.

Query Child Records From Parent

Let’s again reuse the custom object Region__c which we have shared above.

We will be querying the child contact records from the parent Region__c.

// Query Child Records From Parent        
List<Region__c> regionList = [SELECT Id, (SELECT Id, Name from Contacts__r) FROM Region__c LIMIT 100];

// Iterating On The Returned List 
for(Region__c region : regionList) {
    for(Contact con : region.Contacts__r ) {
        System.debug('Contact Name ' + con.Name);        
    }
}

In the above code block, we are querying child Contact records with the relationship Contacts__r inside the brackets.

We can get the child relationship by going to the field definition and looking for the child relationship name. Please refer to the below image :

SOQL Relationship Queries

As seen in the image even though the Child Relationship Name was Contacts, we have used Contacts__r in the above query because if we have to use a custom relationship then it’s required for us to append the ‘__r’ after the custom relationship name.

The total number of rows returned while querying child records from parents is equal to the sum of the number of rows returned for parents and the number of rows returned for child records.

For Example, in our query above if we have a single Region__c record linked to a single contact record. Thus, post executing the above relationship query total number of returned rows will be equal to 2.

Limitations for Relationship Query

There are certain limitations to which the SOQL relationship queries have to adhere.

Salesforce developer docs covered them in a crisp and precise way 🙂

Please refer to the below link once to get more insights on the relationship query limitations.

SOQL Relationship Query Limitation Official Docs

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *