In the last blog, we looked at a simple SOQL query (for one object). And in this one, we will look at SOQL queries to get records from one or more related objects.
Scenario 1: (Child to Parent)
SELECT Id, LastName, AccountId, Account.Name FROM Contact
In this scenario, we are querying on child (Contact) object but also fetching some required information from its parent (Account) object. If there is a need to access more information from the parent, it could be queried as simple as ParentObject.FieldAPIName1, ParentObject.FieldAPIName2 and so on.
Scenario 2: (Parent to Child)
SELECT Id, Name, (SELECT Id, LastName FROM Contacts) FROM Account
Let’s consider a scenario where one wants to access all the Contacts related to Account(s). If you noticed
contacts in the sub-query, the API name considered is the plural form. So if you end up writing like below, it would just not work.
SELECT Id, Name, (SELECT Id, LastName FROM Contact) FROM Account
- Relationship queries are not the same as SQL joins. You must have a relationship between objects to create a join in SOQL.
- No more than 55 child-to-parent relationships can be specified in a query. A custom object allows up to 40 relationships, so you can reference all the child-to-parent relationships for a custom object in one query.
- No more than 20 parent-to-child relationships can be specified in a query.
- In each specified relationship, no more than five levels can be specified in a child-to-parent relationship. For example, Contact.Account.Owner.FirstName (three levels).