Newer Version Available

This content describes an older version of this product. View Latest

Merging Records

When you have duplicate lead, contact, or account records in the database, cleaning up your data and consolidating the records might be a good idea. You can merge up to three records of the same sObject type. The merge operation merges up to three records into one of the records, deletes the others, and reparents any related records.

Example

The following shows how to merge an existing Account record into a master account. The account to merge has a related contact, which is moved to the master account record after the merge operation. Also, after merging, the merge record is deleted and only one record remains in the database. This examples starts by creating a list of two accounts and inserts the list. Then it executes queries to get the new account records from the database, and adds a contact to the account to be merged. Next, it merges the two accounts. Finally, it verifies that the contact has been moved to the master account and the second account has been deleted.

1// Insert new accounts
2List<Account> ls = new List<Account>{
3    new Account(name='Acme Inc.'),
4        new Account(name='Acme')
5        };                                        
6insert ls;
7
8// Queries to get the inserted accounts 
9Account masterAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme Inc.' LIMIT 1];
10Account mergeAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
11
12// Add a contact to the account to be merged
13Contact c = new Contact(FirstName='Joe',LastName='Merged');
14c.AccountId = mergeAcct.Id;
15insert c;
16
17try {
18    merge masterAcct mergeAcct;
19} catch (DmlException e) {
20    // Process exception
21    System.debug('An unexpected error has occurred: ' + e.getMessage()); 
22}
23
24// Once the account is merged with the master account,
25// the related contact should be moved to the master record.
26masterAcct = [SELECT Id, Name, (SELECT FirstName,LastName From Contacts) 
27              FROM Account WHERE Name = 'Acme Inc.' LIMIT 1];
28System.assert(masterAcct.getSObjects('Contacts').size() > 0);
29System.assertEquals('Joe', masterAcct.getSObjects('Contacts')[0].get('FirstName'));
30System.assertEquals('Merged', masterAcct.getSObjects('Contacts')[0].get('LastName'));
31
32// Verify that the merge record got deleted
33Account[] result = [SELECT Id, Name FROM Account WHERE Id=:mergeAcct.Id];
34System.assertEquals(0, result.size());

This second example is similar to the previous except that it uses the Database.merge method (instead of the merge statement). The last argument of Database.merge is set to false to have any errors encountered in this operation returned in the merge result instead of getting exceptions. The example merges two accounts into the master account and retrieves the returned results. The example creates a master account and two duplicates, one of which has a child contact. It verifies that after the merge the contact is moved to the master account.

1// Create master account
2Account master = new Account(Name='Account1');
3insert master;
4
5// Create duplicate accounts
6Account[] duplicates = new Account[]{
7    // Duplicate account 
8    new Account(Name='Account1, Inc.'),
9    // Second duplicate account
10    new Account(Name='Account 1')
11};
12insert duplicates;
13
14// Create child contact and associate it with first account
15Contact c = new Contact(firstname='Joe',lastname='Smith', accountId=duplicates[0].Id);
16insert c;
17
18
19
20// Get the account contact relation ID, which is created when a contact is created on "Account1, Inc." 
21AccountContactRelation resultAcrel = [SELECT Id FROM AccountContactRelation WHERE ContactId=:c.Id LIMIT 1];
22
23
24// Merge accounts into master
25Database.MergeResult[] results = Database.merge(master, duplicates, false);
26
27for(Database.MergeResult res : results) {
28    if (res.isSuccess()) {
29        // Get the master ID from the result and validate it
30        System.debug('Master record ID: ' + res.getId());
31        System.assertEquals(master.Id, res.getId());              
32        
33        // Get the IDs of the merged records and display them
34        List<Id> mergedIds = res.getMergedRecordIds();
35        System.debug('IDs of merged records: ' + mergedIds);                
36        
37        // Get the ID of the reparented record and 
38        // validate that this the contact ID.
39        System.debug('Reparented record ID: ' + res.getUpdatedRelatedIds());
40
41	 // Make sure there are two IDs (contact ID and account contact relation ID); the order isn't defined
42        System.assertEquals(2, res.getUpdatedRelatedIds().size() );    
43        boolean flag1 = false;
44	boolean flag2 = false;
45
46
47    	// Because the order of the IDs isn't defined, the ID can be at index 0 or 1 of the array	     
48        if (resultAcrel.id == res.getUpdatedRelatedIds()[0] || resultAcrel.id == res.getUpdatedRelatedIds()[1] )
49            	flag1 = true;
50        
51       if (c.id == res.getUpdatedRelatedIds()[0] || c.id == res.getUpdatedRelatedIds()[1] )
52            flag2 = true;
53            
54        System.assertEquals(flag1, true); 
55        System.assertEquals(flag2, true);  
56            
57    }
58    else {
59        for(Database.Error err : res.getErrors()) {
60            // Write each error to the debug output
61            System.debug(err.getMessage());
62        }
63    }
64}

Merge Considerations

When merging sObject records, consider the following rules and guidelines:
  • Only leads, contacts, and accounts can be merged. See sObjects That Don’t Support DML Operations.
  • You can pass a master record and up to two additional sObject records to a single merge method.
  • Using the Apex merge operation, field values on the master record always supersede the corresponding field values on the records to be merged. To preserve a merged record field value, simply set this field value on the master sObject before performing the merge.
  • External ID fields can’t be used with merge.

For more information on merging leads, contacts and accounts, see the Salesforce online help.