For Standard Objects:

SELECT (SELECT child_obj_field FROM child_relationship_name) FROM parent_object;

List<Account> accList = [select name, numberOfEmployees, (select name, amount,

closeDate from opportunities) from Account];

  for(Account a: accList)

  {

System.debug(‘ACC: ’ + a.name + ’ NoEMpl: ’+a.numberOfEmployees.;

List<Opportunity> oplist = a.opportunities;

for(opportunity o: oplist)

{

System.debug(‘opportunity name:’ + o.name + ‘Amount: ’+a.amount);

}

  }

For Custom Objects:

SELECT (SELECT child_obj_field FROM (child_relationship_name)__r)

FROM parent_object;

List<Bank__c> bankList = [select Bank_Name__c, (select Branch_ID__c, Name,

State__c from Branches__r) from Bank__c];

for(Bank__c ba: bankList)

{

List<Branch__c> branchList = ba.branches__r;

for(Branch__c br: branchList)

{

System.debug(‘Bank:’+ba.Bank_Name__c+’|Branch ID:’+br.Branch_ID__c

+’|Branch Name:’+br.Name+’|Branch State:’+br.State__c);

       }

}

Note: You can not write a subquery inside a subquery in SOQL.

Our Recent Blog

Share This Post