Site icon Salesforce Binge

SOQL Query. Easy? – Part 2

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

Exit mobile version