Salesforce SOQL Subquery and Custom Objects with Apex

Recently I was dealing with attempting to query a custom object and also its child custom object using a subquery.  The only place that the official Apex Language Reference mentions subqueries is in the Dynamic DML section, and it doesn’t provide any concrete examples for a SOQL statement with a subquery, wrapped in Apex using Custom Objects.

Here’s an example that would have saved me some time.

Two objects,

  • ObjectMaster__c with no new fields (relevant to this example)
  • ObjectDetail__c with one relevant new field
    • Type Master Detail to ObjectMaster__c, API Name ObjectMaster__c, Child Relationship Name on the ObjectMaster__c custom object is “ObjectDetails” (this is important).

A sample Soql query to pull this data is as follows:

Select
  Name,
  (Select Name from ObjectDetails__r)
From
  ObjectMaster__c

This is how the results look in Soql Xplorer:

The following Apex code — tested from the Debug log — queries these SObjects and instantiates them.

for (ObjectMaster__c master : [
    Select
      Name,
      (Select Name from ObjectDetails__r)
    From
      ObjectMaster__c]) {
  System.debug('Here is an ObjectMaster record: '+master);
  for (ObjectDetail__c detail : master.ObjectDetails__r) {
    System.debug('Here is an ObjectDetail record: '+detail);
  }
}

It works!

This entry was tagged , , , , . Bookmark the permalink.

2 Responses to Salesforce SOQL Subquery and Custom Objects with Apex

  1. Pingback: Using SOQL Subquery to Count Child Records | Cloud Clod

  2. NT says:

    Thank you so so much for the explanation. I was looking for how to look for a child object and this post is just a perfect explanation.

Comments are closed.