Sub topic 13
Merging the duplicates you find
Duplicate rules and matching rules find duplicates. Merging is the step that removes them. This chapter covers how a merge works, what happens to the data, and how to merge from the UI and from Apex.
This chapter assumes you have read the earlier chapters on duplicate rules, rule actions, and duplicate record sets. It also assumes you know basic Apex and SOQL for the code sections.
What a merge does
A merge combines two or three records of the same object into one surviving record. You choose which record survives. That record is the master record. The others are the losing records.
During a merge, Salesforce does the following:
- Keeps the master record's Id.
- Lets you pick, field by field, which value the master ends up with.
- Reassigns related records from the losing records to the master. Examples are activities, opportunities, notes, and attachments.
- Deletes the losing records. They go to the Recycle Bin and keep a reference to the master in their
MasterRecordIdfield.
Merging is not reversible in practice. The master's field values are overwritten with your choices, and the losing records are deleted. Treat it as a destructive action.
Which objects can be merged
Merging is available for accounts, contacts, and leads. Apex merge supports those three objects and also cases. Custom objects cannot be merged through the standard merge feature.
Some limits apply to every merge:
- You can merge at most three records at once. To merge more, merge in several rounds.
- All records must be the same object. A lead and a contact cannot be merged. Use lead conversion for that case.
- Converted leads cannot be merged.
- You need permission to delete the losing records, because the merge deletes them.
- Account merges do not merge the child contacts. The contacts move to the master account, and you may then have duplicate contacts to merge in a second step.
Finding records to merge
Duplicate rules do not merge anything on their own. They only produce candidates. There are three common routes to a merge.
- Duplicate record sets. A rule whose action is set to report creates a
DuplicateRecordSetandDuplicateRecordItemrecords. Open a set, select the records, and start the merge from there. - The Potential Duplicates component. An admin can add it to a record page in Lightning App Builder. It shows records that a rule considers duplicates of the one you are viewing, and it offers a merge action.
- The merge pages for an object. For example, the Merge Accounts page lets a user search for records and merge up to three of them.
If you work from sets, this query returns the records in one set:
SELECT Id, DuplicateRecordSetId, RecordId
FROM DuplicateRecordItem
WHERE DuplicateRecordSetId = :duplicateSetIdSets only exist for rules that report. If you want sets to review later, the rule must have the report action turned on. A rule that only alerts or blocks creates no set.
Choosing the master record
The wizard asks you to pick a master. The choice matters because the master keeps its Id, and anything outside Salesforce that stores that Id keeps working. Integrations, external system keys, and bookmarked links all point to the master.
Common ways to pick a master:
| Criterion | Reason |
|---|---|
| Oldest record | Most likely to be referenced by other systems and reports |
| Record with the most related data | Fewer records to reassign |
| Record owned by the right team | Avoids ownership changes after the merge |
| Record synced with an external system | Keeps the external key mapping intact |
After you pick the master, the wizard shows every field where the records differ. Select the value you want for each field. Fields where all records agree, or where only one has a value, need no choice. Review each field with a value on a losing record, because the master's value wins by default.
What gets lost and what gets kept
Related records are moved, not copied. A few things need attention.
- Field values on losing records. Any value you do not select is deleted along with the record.
- Automation. Delete triggers fire for the losing records. Update triggers fire for the master. Flows and processes on those events also run, so a merge can cause side effects such as notifications or integration calls.
- Sharing. The master keeps its own owner and sharing. Records moved from the losing records keep their relationship, but they may become visible to different people.
- History. Field history of a losing record is not carried over to the master.
Merging in Apex
Apex has a merge statement and a Database.merge method. Both take a master record and up to two records to merge into it. The losing records are deleted and their related records move to the master.
The master's field values are kept as they are. Salesforce does not choose values for you. To keep a value from a losing record, set it on the master and update the master first.
The following class loads the records in a duplicate record set. It keeps the oldest contact as the master and copies a phone number from a loser if the master has none. It then merges.
public with sharing class DuplicateSetMerger {
public static void mergeContactSet(Id duplicateSetId) {
Set<Id> recordIds = new Set<Id>();
for (DuplicateRecordItem item : [
SELECT RecordId
FROM DuplicateRecordItem
WHERE DuplicateRecordSetId = :duplicateSetId
]) {
recordIds.add(item.RecordId);
}
List<Contact> contacts = [
SELECT Id, Phone, CreatedDate
FROM Contact
WHERE Id IN :recordIds
ORDER BY CreatedDate ASC
];
// One merge handles a master plus at most two losing records.
if (contacts.size() < 2 || contacts.size() > 3) {
return;
}
Contact master = contacts[0];
List<Id> loserIds = new List<Id>();
for (Integer i = 1; i < contacts.size(); i++) {
if (master.Phone == null && contacts[i].Phone != null) {
master.Phone = contacts[i].Phone;
}
loserIds.add(contacts[i].Id);
}
update master;
List<Database.MergeResult> results = Database.merge(master, loserIds, false);
for (Database.MergeResult result : results) {
if (!result.isSuccess()) {
for (Database.Error err : result.getErrors()) {
System.debug('Merge failed: ' + err.getMessage());
}
}
}
}
}The false argument turns off all-or-none behavior, so a failure returns an error in the result and does not throw an exception. Check each result, as the loop above does.
Keep these points in mind when writing merge code:
- Each merge call handles at most three records. A set of ten needs several calls, with each round merging into the same master.
- Merges count against DML limits. Do not merge inside a loop over many sets without checking governor limits.
- To find the losing records after a merge, query with
ALL ROWSand filter onMasterRecordId.
Common problems
- The Merge button is missing. Check that the user has delete permission on the object and that the records are the same object and not converted leads.
- A contact merge is refused. Contacts that belong to different accounts often cannot be merged directly. Move the contacts under one account first, or merge the accounts.
- Duplicates keep coming back. Merging cleans up records that already exist. It does not stop new duplicates. Check that the duplicate rule is active and that its matching rule covers the data that is arriving.
- Unexpected emails or integration calls. The delete and update events caused by the merge triggered automation. Review flows and triggers on those events.
Exercise
A duplicate rule alerts users when they create a contact that matches an existing one, but no duplicate record sets appear in the org. Users must still merge the duplicates later. What change makes sets appear, and why can an Apex merge not use the Recycle Bin as an undo?
Show answer
Turn on the report action for the duplicate rule, so that matches create DuplicateRecordSet and DuplicateRecordItem records. An alert-only rule creates no sets. A merge cannot be undone from the Recycle Bin because the master record's field values are overwritten during the merge. Restoring a deleted losing record would not bring back the previous master values or move the related records back.