SOQL Relationships - Parent to Child SOQL | Child to Parent SOQL for Standard and Custom Object - SOQL Basic | Salesforce Funda

SOQL allows you to query and retrieve data from Salesforce objects and their relationships. SOQL Relationships between objects are mainly used to query the records from one or more objects in a single SOQL statement in salesforce.com

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


There are two types of relationship queries :
1. Child To Parent Relationship
2. Parent To Child Relationship
3. Self-Relationships
4. Querying Related Objects

Parent-to-Child Relationship: Use dot notation to traverse from a parent object to its related child objects. This query retrieves the Name field from the Account object and the FirstName and LastName fields from the related Contact objects.

SOQL Syntax :- 

SELECT Name, (SELECT FirstName, LastName FROM Contacts) FROM Account

Child-to-Parent Relationship: Use relationship names to traverse from a child object to its parent object. This query retrieves the Name field from the parent Account object of the Contact object.

SOQL Syntax :-

SELECT Contact.Account.Name FROM Contact

Self-Relationships: You can query objects that have a self-relationship, where records within the same object are related to each other.Use relationship names to traverse between records in the same object.
This query retrieves the Name field from the Parent__c object and the Name field from its related child records,  where the relationship is defined by the Children__r relationship name.

SOQL Syntax :-

SELECT Name, (SELECT Name FROM Children__r) FROM Parent__c

Querying Related Objects :- You can query related objects using relationship fields defined in the object schema. This query retrieves the Name field from the related Account object and the Subject field from the related Task objects for each Opportunity record.

SOQL Syntax :-

SELECT Account.Name, (SELECT Subject FROM Tasks) FROM Opportunity

Parent Query

SELECT Account.Name, (SELECT Subject FROM Tasks) FROM Opportunity

Parent to Child for Standard Object and fields :-

SELECT name (SELECT lastname FROM Contacts) FROM Account

Parent to Child for Custom Object and fields :-

SELECT FirstName__c, LastName__c, ( SELECT FirstName__c, LastName__c FROM child__r ) FROM Parent__c

Child Query :-

Child to Parent for Standard Object and fields :-

SELECT id, Name, Account.name FROM Contact WHERE Account.Industry = ‘ Media’

Child to Parent for Custom Object and fields :-

SELECT Id, Firstname__c, Parent__r.firstname__c FROM Child__c WHERE Parent__r.Lastname__c LIKE ‘c%’

feature :-