function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
hramanihramani 

Database.query returning Id of relationship query but I need name.

I have a string variable of an SOQL query where I have a relationship query name but the output returns only the relationship Id. Below is the query and the output in detail.

String s = 'select XYZ__r.Name from contact where Id = \'0031D00000KkQLKQA3\'';
system.debug(Database.query(s));

Output : (Contact:{XYZ__c=a0w1D000000RezuQAC, Id=0031D00000KkQLKQA3})

How do I get the XYZ__r.Name in the output. 
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

If you use a debug statement to view the output, then you will only see the Ids. However, you will be able to reference the actual names. When you debug the list it will only show the reference to the related record.
You will need to debug the individual XYZ__r.Name from each record to get the names, or store them in a collection like this:
 
String s = 'Select Id, Name, XYZ__r.Name from contact where Id = \'0031D00000KkQLKQA3\'';
System.debug(Database.query(s));

List<Contact> cList = Database.query(s);
for(Contact con : cList){
    system.debug(con.XYZ__r.Name);
}

The debug statement will correctly display the Name and not the Id.

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Avish Samdani 5Avish Samdani 5
Hi,

In debug statement only Id values will display for relationship fields. To get relationship fields you need to provide the actual reference for that field.
If you need to debug XYZ's Name then 'XYZ__r.Name' will print name.
String s = 'Select Id, Name, XYZ__c, XYZ__r.Name from contact where Id = \'0031D00000KkQLKQA3\'';

List<Contact> cList = Database.query(s);
for(Contact con : cList){
    system.debug(con.XYZ__r.Name); // Display Name
    System.debug(con); // Will display Id of XYZ
}
OR
String s = 'Select Id, Name, XYZ__c, XYZ__r.Name from contact where Id = \'0031D00000KkQLKQA3\'';

List<sObject> cList = Database.query(s);
for(sObject con : cList){
    System.debug(con.getSObject('XYZ__c').get('Name')); // Display Name
}


I hope this helps you. If My answer resolve your issue please mark best answer
Akinsola Jegede 23Akinsola Jegede 23
@KhanAnas  and  @AvishSamdani 5 Solution works. Can you mark the answer as correct?