[SalesForce] SOQL: Access Referenced object from a lookup field

I had an instance where I created a lookup field on a custom object (i.e. Sale__c) to reference an Opportunity, in which case this created a relationship for the Opportunity. Meaning I could now SOQL any related custom objects using the plural API name and a "__r" suffix like so:

SELECT Id, (SELECT Id FROM Customs__r) FROM Opportunity

But for my scenario the question was about using this relationship the other direction. When writing a query on the custom Sale__c object there is no relationship for me to use Opportunities__r like so:

SELECT Id, (SELECT Id FROM Opportunities__r) FROM Sale__c

Best Answer

In this instance you can refer to the singular API name with a "__r" suffix without needing a nested relationship query, like so:

SELECT Id, Opportunity__r.CloseDate FROM Sale__c

As mentioned here: Access Id of Contact from lookup field this approach is not necessary when fetching the reference ID, but when you need to select other fields from that object this would be the approach.

Related Topic