I need an SOQL query to find all the fields in an Object which are referencing to other Objects. For Example

Account is an sObject which has different fields which refer to the other sObjects. The SOQL query should be such that all the related sObjects should be listed when we look for any sObject.

[Account] -> [Contact, AccountContactRole, Case, Asset, Contract, Order, Opportunity]

  • 1
    SOQL is not, IMHO, the right way to get this information. Instead you should be using the metadata API or the Apex Schema access.
    – Phil W
    Feb 26 at 12:23
  • If the need is to show specifically the values of all the lookup fields, then you can use the metadata API or Schema class like Phil W suggested and use that to construct a dynamic query.
    – nbrown
    Feb 26 at 13:58

I think SOQL query won't be able to provide for this instead use the Dynamic apex to find out about the lookup fields for the current object (Which is basically the fields on the current object pointing to other object) and then u can apply dynamic query on using all the lookup

String objectName = 'Opportunity';
String fieldName = 'AccountId';

SObjectType r = ((SObject)(Type.forName('Schema.'+objectName).newInstance())).getSObjectType();
DescribeSObjectResult d = r.getDescribe();

.getType() will provide the lookup fields with value "REFERENCE".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.