In Salesforce, we often encounter difficulties in managing duplicate records of Salesforce objects, such as Opportunities, Leads, Accounts, and Contacts, which can result in complications for data management.
To handle this situation, merging these records is crucial for maintaining a clean database and integrating data effectively.
In this Salesforce tutorial, we will learn how to merge records in Salesforce Apex using the following methods.
- Using the merge statement.
- Using the Database.merge() method.
Merge Records using the ‘merge’ statement in Salesforce Apex
In Salesforce Apex, the simplest way to merge records is using merge statements. This method allows for the merging of up to three records of the same type. It deletes the duplicates and combines them with the master records, along with the related records.
In this example, we will merge two contact records using the ‘merge’ statement, retaining all related records under the primary record, including activities, opportunities, and cases.
Apex code:
public class ContactMerger {
public static void mergeContacts(Id primaryContactId, Id duplicateContactId) {
try {
Contact primaryContact = [SELECT Id, FirstName, LastName, Email FROM Contact WHERE Id = :primaryContactId LIMIT 1];
Contact duplicateContact = [SELECT Id, FirstName, LastName, Email FROM Contact WHERE Id = :duplicateContactId LIMIT 1];
merge primaryContact duplicateContact;
System.debug('Merge successful: ' + primaryContactId + ' retains the data, and ' + duplicateContactId + ' is merged.');
} catch (DmlException e) {
System.debug('Merge failed: ' + e.getMessage());
}
}
}Call the method with an anonymous code:
Id primaryId = '003J3000008lBSdIAM';
Id duplicateId = '003J300000CYAnHIAX';
ContactMerger.mergeContacts(primaryId, duplicateId);Output:

As we can see, the output of the duplicate contact record is deleted and merged with the primary contact record.
Merge Records using the Database.merge() method in Salesforce Apex
In Salesforce Apex, the Database.merge() method offers an alternative to handling errors more efficiently than the standard merge statement.
In this example, we will merge the two account records into a single record using the Database.merge() method.
public class AccountMerger {
public static void mergeAccounts(Id primaryAccountId, Id duplicateAccountId) {
try {
Account primaryAccount = [SELECT Id, Name, Industry, Phone FROM Account WHERE Id = :primaryAccountId LIMIT 1];
Account duplicateAccount = [SELECT Id, Name, Industry, Phone FROM Account WHERE Id = :duplicateAccountId LIMIT 1];
Database.SaveResult mergeResult = Database.merge(primaryAccount, new List<Account>{duplicateAccount}, false);
if (mergeResult.isSuccess()) {
System.debug('Merge successful: Primary Account ID ' + primaryAccountId + ' now includes data from Duplicate Account ID ' + duplicateAccountId);
} else {
for (Database.Error error : mergeResult.getErrors()) {
System.debug('Merge failed due to error: ' + error.getMessage());
}
}
} catch (Exception e) {
System.debug('An unexpected error occurred during the merge: ' + e.getMessage());
}
}
}Call the method with an anonymous code:
Id primaryAccountId = '0015i00000lU1htAAC';
Id duplicateAccountId = '001J3000007zBBkIAM';
AccountMerger.mergeAccounts(primaryAccountId, duplicateAccountId);Output:

In the output, we can see that the duplicate account has been merged with the primary account, along with its related fields.
This way, we can merge records in Salesforce Apex using the Database.merge() method.
Difference between Merge and Database.merge methods in Apex
The working of both methods, merge and database, is efficient for merging records in Salesforce using Apex. Now, we will see the differences between these two methods.
Merge method: The Salesforce Apex merge statement is used for simple merge operations, suitable for scenarios requiring minimal customization and error handling.
It directly throws exceptions if any errors occur during the merge, which means that the process will halt if an error is encountered. This feature is beneficial when working with simple merges, which involve merging up to three records and do not require advanced error-handling capabilities.
Database.merge(): This method provides greater control and flexibility, particularly with error handling. Instead of throwing exceptions directly, it captures errors in a MergeResult object, allowing us to review and handle issues more efficiently without interrupting the execution flow.
This method is helpful in complex scenarios where error handling is critical. It supports merging up to three records while ensuring that execution continues even when errors are encountered, enhancing the user experience.
Conclusion
In Salesforce, merge and database merge methods allow you to efficiently perform data merge operations and handle duplicate records through Apex. For simple merge operations, use merge; for complex merge operations, use database.merge.
By now, you might have understood the method of merging records in Salesforce using the above methods. You can efficiently manage and merge the duplicate records in your Salesforce instance.
You may also like to read:
- Define and Use Constants in Salesforce Apex Classes
- Abstraction in Salesforce Apex
- Create and Use Constructors in Salesforce Apex Classes
- Salesforce Administrator Login as User: Add a Login Button
- Before Insert Validation in Salesforce Trigger [With Examples]
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.