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
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 AccountChild-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 ContactSelf-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__cQuerying 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 OpportunityParent Query
SELECT Account.Name, (SELECT Subject FROM Tasks) FROM OpportunityParent to Child for Standard Object and fields :-
SELECT name (SELECT lastname FROM Contacts) FROM AccountParent to Child for Custom Object and fields :-
SELECT FirstName__c, LastName__c, ( SELECT FirstName__c, LastName__c FROM child__r ) FROM Parent__cChild 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 :-
