How to get key prefix of an object using Apex in Salesforce

GOAL

  • The first three digits of any record Id is same for an Object and represents the SObject. For example, the Account object uses the 001 prefix; the Lead object uses the 00Q prefix, Contact uses 003 and custom object uses whatever Salesforce generates.
  • The key prefixes for all the standard objects remain the same in all Salesforce orgs the same but It changes org to org for Custom Object. So, sometimes in code, we need to check the object type and perform action based on conditionally.
  • I’ve see people using hard-coded check like recordId.startsWith(‘0a1’) and it get broken when this logic is applied for Custom object and get broken when changes deployed to a new Salesforce org.
  • So It’s crucial to know best way that will remove this hard-coded check and run based on current org.

SOLUTION

GET OBJECT API NAME BASED ON RECORD ID
Id recordId = '00QTA000003L4n9';
String objApiName = recordId.getSObjectType().getDescribe().getName();
GET OBJECT KEY PREFIX BASED ON OBJECT API NAME
public static String getObjectKeyPrefix(String objName){
    /*objName ='Account';*/
    schema.sObjectType sObjType = Schema.getGlobalDescribe().get(objName);
    return (sObjType.getDescribe().getKeyPrefix());
}