salesforce Apex How to convert a 15-digit record ID to an 18-digit record and vice versa?
•10 min read

In Salesforce, the 15-digit ID is case-sensitive while the 18-digit ID is case-insensitive (the extra 3 characters form a checksum). Here's how to convert between them in Apex:
15-digit → 18-digit
This is straight forward since Salesforce's Id type automatically handles it:
apex
// Method 1: Direct cast
String id15 = '001D000000IqhSL';
Id id18 = (Id) id15;
System.debug(id18); // 001D000000IqhSLIAZ
// Method 2: Using String.valueOf()
String id18String = String.valueOf((Id) id15);JavaScript18-digit → 15-digit
Simply truncate the string to 15 characters:
apex
String id18 = '001D000000IqhSLIAZ';
String id15 = id18.substring(0, 15);
System.debug(id15); // 001D000000IqhSLJavaScriptUtility Class Example
apex
public class IdConverter {
// Convert 15-digit to 18-digit
public static String to18Digit(String id15) {
if (String.isBlank(id15)) return null;
if (id15.length() == 18) return id15;
if (id15.length() != 15) {
throw new IllegalArgumentException('Invalid ID length: ' + id15.length());
}
return String.valueOf((Id) id15);
}
// Convert 18-digit to 15-digit
public static String to15Digit(String id18) {
if (String.isBlank(id18)) return null;
if (id18.length() == 15) return id18;
if (id18.length() != 18) {
throw new IllegalArgumentException('Invalid ID length: ' + id18.length());
}
return id18.substring(0, 15);
}
}JavaScriptKey Points
| Aspect | 15-digit | 18-digit |
| Case sensitivity | Case-sensitive | Case-insensitive |
| Use case | UI, URLs | Apex, APIs, integrations |
| SOQL comparison | Works but risky | Recommended |
Best practice: Always use 18-digit IDs in Apex code and integrations to avoid case-sensitivity issues, especially when comparing IDs from external systems or CSV imports.
Related Posts

How to Automatically create a follow-up Task when a Lead is converted

How You need to update a related child record whenever a parent record’s status changes, but only if the status is “Closed Won.” How would you design this in Apex?
