Relationship Queries #inSalesforce

1. Child To Parent Relationship or Upwards Traversal

If there's a lookup or master-detail field from the base object.

Example 1:

SELECT Id, Account.Name, Account.Industry, Account.Website FROM Contact WHERE Account.NumberOfEmployees > 100

This is like when in flow or formula fields, you are able to reference the contact’s account fields by using the same dot notation.

Example 2: 

SELECT Account.Owner.Profile.CreatedBy.Name FROM Contact

This is like querying contacts, upwards traversal could pull data from the contact’s account.


Traverse multiple levels upwards:

Suppose you are traversing a custom lookup field Contact__c on the Favorite__c object. 

Example 3:

SELECT Id, Contact__r.countofChild__c FROM Favorite__c

Here Parent is Contact and Child is Favorite__c

Note the use of __r and __c above or refer - https://thesalesforcetutorial.blogspot.com/2021/08/whats-difference-between-c-and-r.html


2. Parent To Child Relationship or Downwards Traversal:

If you’re pulling records from a related lists.

Example 1:

SOQL query on accounts, downwards traversal could pull data from the account’s related contacts -

SELECT Id, Name, Industry, AnnualRevenue,(SELECT Name, BirthDate FROM Contacts) FROM Account

First name is the normal query for Account, and the other one pulling the Account's contact related list.

Note, here the nested query '(SELECT Name, BirthDate FROM Contacts)' is treated like another field. That’s why there is a comma after the AnnualRevenue field.

Plural version 'Contacts' in the nested SOQL query (refers the child(s) or Contacts of Account or parent).

Example 2:

SELECT Id, Name, Account.Description, CreatedBy.Name,(SELECT Amount FROM Opportunities WHERE Amount > 1000) FROM Contact where Account.Id != null


Visual: https://www.youtube.com/watch?v=GWyppUUg-_4

Comments