Relationship Queries

Relationship queries involve at least two objects, a parent and a child. These queries are used to fetch data either from the Parent object, when SOQL query is written on child, or from child object when SOQL query is written on parent.

Child to Parent:

For Standard Objects:

SELECT relationship_field.parent_obj_field FROM child_object;

List<Opportunity> oppList = [SELECT name, amount, closeDate, account.name

FROM Opportunity];

  for(Opportunity o: oppList)

  {

System.debug(‘Opp: ‘ + o.name  + ‘ Acc: ‘+o.account.name);

  }

For Custom Objects:

SELECT (relationship_field)__r.parent_obj_field FROM child_object;

List<Branch__c> branchList = [select Branch_ID__c, State__c,

Branch_of_Bank__r.Bank_Name__c from Branch__c];

  for(Branch__c bl: branchList)

  {

System.debug(‘Bank Name: ‘+bl.Branch_of_Bank__r.Bank_Name__c

+ ‘Branch: ‘+bl.State__c);

  }

Our Recent Blog

Share This Post