Apex trigger fails during contact merge when duplicate rule enforcement blocks operation

We’re experiencing a critical issue with our contact merge automation. Our Apex trigger that handles post-merge data cleanup is throwing an unhandled DmlException when duplicate rules are active. The trigger works perfectly in our sandbox where duplicate rules are disabled, but fails in production.

The error occurs specifically when merging contacts that would violate our duplicate prevention rules. The trigger doesn’t properly handle the Database.merge allOrNone flag, causing the entire transaction to roll back.

Contact master = [SELECT Id FROM Contact WHERE Id = :masterId];
List<Contact> duplicates = [SELECT Id FROM Contact WHERE Id IN :dupeIds];
Database.merge(master, duplicates);
// Post-merge cleanup logic here

This is blocking our sales team from consolidating duplicate records during data quality initiatives. Any guidance on proper error handling for merge operations with duplicate rule enforcement would be greatly appreciated.

Here’s a comprehensive solution that addresses all three focus areas: proper error handling, duplicate rule enforcement awareness, and correct use of the allOrNone flag.

First, modify your merge operation to use the allOrNone parameter set to false. This allows you to process successful merges while capturing failures:

Database.MergeResult[] results = Database.merge(master, duplicates, false);
for(Database.MergeResult result : results) {
    if(!result.isSuccess()) {
        for(Database.Error err : result.getErrors()) {
            System.debug('Merge failed: ' + err.getMessage());
        }
    }
}

Second, implement duplicate rule checking before the merge. Query active duplicate rules and their criteria to understand what might cause conflicts. You can use the DuplicateRule and DuplicateRuleMatchRule objects to inspect the active rules programmatically.

Third, wrap your merge logic in proper exception handling that specifically catches DmlException and inspects the error type. For duplicate rule violations, the error code will be DUPLICATE_VALUE. Your trigger should handle this gracefully:

try {
    Database.MergeResult[] results = Database.merge(master, duplicates, false);
    // Process results and handle errors
} catch(DmlException e) {
    for(Integer i = 0; i < e.getNumDml(); i++) {
        if(e.getDmlType(i) == StatusCode.DUPLICATE_VALUE) {
            // Handle duplicate rule violation
            System.debug('Duplicate rule violated: ' + e.getDmlMessage(i));
        }
    }
}

Additionally, consider implementing a Database.DMLOptions approach where you can specify allowDuplicates = true for specific merge operations that should bypass duplicate rules. This is useful for automated data quality processes where you’ve already validated the merge candidates.

For your post-merge cleanup logic, ensure it only executes for successful merges by checking the MergeResult.isSuccess() flag. This prevents your cleanup code from running on failed merge attempts.

Finally, implement comprehensive logging that captures the duplicate rule name, the matched records, and the specific criteria that triggered the violation. This will help your sales team understand why certain merges fail and allow them to make informed decisions about data quality exceptions.

The key insight is that Database.merge with allOrNone=false gives you granular control over partial success scenarios, while proper exception handling and duplicate rule awareness ensure your automation is robust in production environments with active data quality rules.


This draft is based on general Salesforce knowledge. It has not been verified against your specific version and environment. Practitioners: verify the steps and share your experience below.

The issue stems from how Database.merge interacts with duplicate rules. When you don’t specify the allOrNone parameter, it defaults to true, meaning any DML failure rolls back the entire operation. You need to implement proper exception handling and consider the duplicate rule context. Have you checked the DuplicateError details in the Database.SaveResult? That will tell you exactly which rule is being violated.

I’ve seen this pattern before. The duplicate rules are evaluated during the merge operation, not just on insert/update. Your trigger needs to catch the DmlException and inspect the error type. Consider wrapping your merge in a try-catch block and logging the specific duplicate rule violations. You might also want to query the DuplicateRule object to understand which rules are active and their criteria before attempting the merge.

Quick question - are you using Database.merge with the allOrNone flag set to false? That would allow partial success and give you more control over error handling. Also, make sure you’re checking the DuplicateRecordItem objects after the merge attempt. These contain the matched duplicate records and the rules that triggered.

“Tested this on Salesforce Spring '24 with Contact merges—setting allOrNone to false in Database.merge successfully isolated duplicate rule failures without rolling back valid merges.”

The duplicate rule enforcement happens at the database layer, so your trigger execution order matters. If you have before/after triggers on Contact, they all need to handle the duplicate rule scenario. I’d recommend implementing a custom exception handler that specifically catches duplicate rule violations and provides meaningful feedback to users. You could also consider temporarily disabling duplicate rules for automated merge processes if that aligns with your data governance policies.

This is a common gotcha with merge operations. The Database.merge method doesn’t give you the same level of control as Database.update when it comes to duplicate rules. One approach is to query the DuplicateRecordSet and DuplicateRecordItem objects before attempting the merge to identify potential conflicts. You could then either bypass the rules using DML options or handle the specific scenarios in your code. The key is understanding which duplicate matching rules are active and how they evaluate your contact data.