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
eliotstock2eliotstock2 

query for an SObject knwoing its Id but not its type

Hi there.

 

I'm trying to build a tool for monitoring various records udring QA. Is there any way to query for an SObject knowing only its Id and not its type?

 

Thanks,

 

Eliot Stock.

Best Answer chosen by Admin (Salesforce Developers) 
David VPDavid VP

You can get to the objectname if you just know it's key prefix (3 first characters of the Id).

 

Drop the following in an anonymous block and you'll see what I mean :

 

Map<String, Schema.SObjectType> res = Schema.getGlobalDescribe(); for(String sotkey:res.keySet()) { Schema.DescribeSObjectResult dso = res.get(sotkey).getDescribe(); System.debug(dso.getKeyPrefix() + ' : ' + dso.getName()); }

 

From here it's easy to create a Map with as keys the prefixes and as values the object names. You can then simply do a map.get(prefix) which will give you back the object name you can use in your dynamic query.

 

 

David

 

 

All Answers

BritishBoyinDCBritishBoyinDC

I don't think so, BUT you can work out the object by looking at the first three characters of the URL - so an Id like 006R0000004Rnlx is always a contribution I believe.

 

So you could create a lookup table in QA that stores the object name and the first three characters of the ID, and work it out that way to create some dynamic SOQL... 

David VPDavid VP

You can get to the objectname if you just know it's key prefix (3 first characters of the Id).

 

Drop the following in an anonymous block and you'll see what I mean :

 

Map<String, Schema.SObjectType> res = Schema.getGlobalDescribe(); for(String sotkey:res.keySet()) { Schema.DescribeSObjectResult dso = res.get(sotkey).getDescribe(); System.debug(dso.getKeyPrefix() + ' : ' + dso.getName()); }

 

From here it's easy to create a Map with as keys the prefixes and as values the object names. You can then simply do a map.get(prefix) which will give you back the object name you can use in your dynamic query.

 

 

David

 

 

This was selected as the best answer
eliotstock2eliotstock2
Thanks, both of you. Great help.