Print this page

How to find Object Type from Record ID Prefix

Knowledge Article Number 000213523
Description There is an existing article that provides list of standard objects for a prefix; Standard Field Record ID Prefix Decoder. This article, however, does not provide a way (as list is not possible) to find object name from record ID prefix.
Resolution You can use following code to find object name based on provided record ID prefix.
public class SchemaGlobalDescribe{
    public static String findObjectNameFromRecordIdPrefix(String recordIdOrPrefix){
        String objectName = '';
            //Get prefix from record ID
            //This assumes that you have passed at least 3 characters
            String myIdPrefix = String.valueOf(recordIdOrPrefix).substring(0,3);
            //Get schema information
            Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe(); 
            //Loop through all the sObject types returned by Schema
            for(Schema.SObjectType stype : gd.values()){
                Schema.DescribeSObjectResult r = stype.getDescribe();
                String prefix = r.getKeyPrefix();
                System.debug('Prefix is ' + prefix);
                //Check if the prefix matches with requested prefix
                if(prefix!=null && prefix.equals(myIdPrefix)){
                    objectName = r.getName();
                    System.debug('Object Name! ' + objectName);
        }catch(Exception e){
        return objectName;

You can easily use this code in developer console:
String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('500');

You can also store this as a class and then create a custom visualforce page if you think you tend to use it more often and need a user friendly method. Of course, in that instance, you need test code coverage. I have written following test class which you can use to cover above code.
private class SchemaGlobalDescribeTests{
    private static void testMethodPositive(){
        String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('500');
    private static void testMethodNegative(){
        String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('500');
    private static void testMethodNull(){
        String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('101');
    private static void testMethodException(){
        String objectName = SchemaGlobalDescribe.findObjectNameFromRecordIdPrefix('10');


promote demote