I need to retrieve an object's info from a single query. Lets say I have 4 objects (A__c, B__c, C__c, D__c). The relationship is that B__c has the master-detail relationship with A__c and B__c is also the child of C__c (lookup relationship). D__c is the child of C__c (Master-detail relationship on D__c).

Now I need to run a query on A__c to get the related details of D__c. I could take out the info till C__c but dont know how to move after that. Please help. Below is the query I have tried:

SELECT (Select ID, Name, C__r.Name FROM B__r)ID, Name from A__c 

1 Answer 1


The only way you're going to get this data in one query is to start from C__c, not A__c. This has to do with the restrictions on how SOQL works; you can only go "down" one level (to children records), but "up" five levels (to great-great-great-grandparent records). Your query would look like this:

SELECT (SELECT ... FROM D__r), (SELECT A__r.Name... FROM B__r) FROM C__c
  • Can we run the query on Object B__c as this the place which has relationship with A__c and C__c? Dec 17, 2018 at 12:05
  • @SalesforceLearner Not if you want to include D in the query. This is the only query that can get all four objects at once.
    – sfdcfox
    Dec 17, 2018 at 12:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .