I am utilizing the Account object to store both the Customer Account and its associated Billing accounts. How do I write a SOQL query to pull all billing accounts related to the customer account.

enter image description here

In the below image you can see the first account as Customer Account and all the below records are billing accounts related with the first Customer. The current relationship is using the Id field of the Customer Account to ParentId field of the Billing Accounts.

How do I write a SOQL to pull in related records if it is in the same object?

2 Answers 2


The following query would help:

SELECT Name, (SELECT Name FROM ChildAccounts) FROM Account

This will find all top-level accounts and their children. Note, however, if you have deeply nested accounts, you'd have to associate the nested children recursively. I have written a few examples, such as this one, this one, and probably others, too. It just requires a Map and a few for loops.

  • That helps, Thanks sfdcfox
    – sumchans
    Commented Feb 5, 2021 at 16:55

You find the child relationship name the same way you would any other:

for (ChildRelationship relation : SObjectType.Account.getChildRelationships())

Comb through the debug logs and you will see getRelationshipName=ChildAccounts for the relevant ChildRelationship.

  • this would be on the same object, is it possible that we could pull the child records through SOQL.
    – sumchans
    Commented Feb 5, 2021 at 1:42
  • Yes it still works like other joins. The syntax and mechanics are the same.
    – Adrian Larson
    Commented Feb 5, 2021 at 1:46
  • Could you provide me with an example using SOQL for the above small data?
    – sumchans
    Commented Feb 5, 2021 at 1:47

You must log in to answer this question.

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