How to get key-prefix of salesforce object?

Sometimes while writing your code in trigger, you need to identify objects based on record id of the record. So, first three character of the recordId which is called key-prefix is used to identify object in code.

For eg. a0u is the keyprefix which is used to identify Custom_Network_Case__c object as shown in below url

https://****.lightning.force.com/lightning/r/Custom_Network_Case__c/a0u2C000001Ne9jQAC/view

Now we will see how can we can get key-prefix of a salesforce object.

If we know the object name already:

String keyPrefix = Custom_Network_Case__c.SObjectType.getDescribe().getKeyPrefix();

System.Debug('Key Prefix: '+ keyPrefix);

If object is dynamically get from the string:

Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get('Custom_Network_Case__c') ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
String keyPrefix = r.getKeyPrefix();
System.Debug('Key Prefix: '+ keyPrefix);

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply