I have the following query:

public List<My_Main_Object__c> data;

data = [Select My_Object__r.Id FROM My_Main_Object__c where id=:XXXX];

How can I pass the result of this query into a variable?

I'm trying the following

public String returnedId;

returnedId = data.My_Object__r.Id;

But I'm getting the following error:

Initial term of field expression must be a concrete SObject: LIST<My_Main_Object__c> 

Can anyone tell me what the issue is here and how I can pass My_Object__r.Id into the returnedId variable??


3 Answers 3


Your [Select My_Object__r.Id FROM My_Main_Object__c where id=:XXXX]; query returning a list of My_Main_Object__c object.

So you will have to do something like

 if(data.size() > 0 ){ 
 returnedId = data[0].My_Object__r.Id; 
  • Excellent!! Cheers man, worked a treat!
    – Daft
    Aug 28, 2014 at 12:06
  • Thanks. Can you please mark it best answer? Aug 28, 2014 at 12:30

In your code data is a list. So the reference to data.My_Object__r.Id is not valid as My_Object__r.Id is an attribute of each element in the list, not the list itself. When you are querying for and the where clause is using Id = XXXX, you can typically just assign to a single instance of an sObject.

Also you are querying an value using a relationship where it is unnecessary. In a custom relationship, the following is always true. object.Related_Object__c == object.Related_Object__r.Id

But the querying for the second is more expensive. So I would suggest the following:

public My_Main_Object__c data;

try { 
  data = [Select My_Object__c FROM My_Main_Object__c where id=:XXXX];
} catch (QueryException) {
  data = new My_Main_Object__c();
  //or handle the possible exception in some other way

if (data.My_Object__c != null){
  returnedId = data.My_Object__c;

In all other cases, the best practice in Apex would be to assign to list, as you were doing iterate over the list to access the data:

data = [Select My_Object__r.Id FROM My_Main_Object__c where XXXX];

for (My_Main_Object__c mo : data){
  returnedId = data.My_Object__c; 
  //or something else

Not treating a list as a list can be problematic.


You can access a field directly from the SOQL using a dot:

Id returnedId = [Select My_Object__r.Id 
                 From My_Main_Object__c 
                 Where id=:XXXX].My_Object__r.Id;

You must log in to answer this question.

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