+ Start a Discussion
Sumant KuchipudiSumant Kuchipudi 

How can we get Object name by ID using SOQL?

Hi,
I can get the Object name with the following code but how can I get this objName using SOQL?
String objName = recId.getSObjectType().getDescribe().getName()
I'm using java/python code to call SOQLs for some other work (integration) I need to know the object names by record ids in Java/Python. Please advice
 
Best Answer chosen by Sumant Kuchipudi
Charisse de BelenCharisse de Belen
Hi Sumant,

I do not think you can do this in SOQL, but as Arvind said, you can query the record ID of the object. The key prefix is the first 3 characters of the record ID. This key prefix will actually tell you the object type of the record, so if you have a map of key prefixes and their matching object types, you can just lookup the key prefix to find the object type.

All Answers

Arvind KumarArvind Kumar
Hi Sumant,

You can easily get the object Name from Record Id:
 
 
public string findObjectAPIName( String recordId ){
        if(recordId == null)
            return null;
        String objectAPIName = '';
        keyPrefix = recordId.substring(0,3);
         for( Schema.SObjectType obj : Schema.getGlobalDescribe().Values() ){
              String prefix = obj.getDescribe().getKeyPrefix();
               if(prefix == keyPrefix){
                         objectAPIName = obj.getDescribe().getName();
                          break;
                }
         }
         return objectAPIName;
}


Use it, if you have any query, you can contact me.

Thanks,
Arvind Kumar

Sumant KuchipudiSumant Kuchipudi
Hi Aravind,
I know how to get obj name from APEX but I'm trying to get it from Java/Python which doesn'r have Schema kinda apex apis so I was looking for an option from SOQL. Please advice
Charisse de BelenCharisse de Belen
Hi Sumant,

I do not think you can do this in SOQL, but as Arvind said, you can query the record ID of the object. The key prefix is the first 3 characters of the record ID. This key prefix will actually tell you the object type of the record, so if you have a map of key prefixes and their matching object types, you can just lookup the key prefix to find the object type.
This was selected as the best answer
Sumant KuchipudiSumant Kuchipudi
Thanks Charisse, I got your idea that maintain Map of key prefixes and it worked. 
Charisse de BelenCharisse de Belen
I am glad to hear it worked, Sumant. When you get the chance, please select the Best Answer so this question can be marked Solved.