How to skip duplicate rules in Salesforce

How to skip duplicate rules in Salesforce
Reading Time: < 1 minute

It is possible to skip or bypass duplicate rules in Apex when using Database.insert sentence.

To bypass duplicate rules in Salesforce using Apex, you can use the Database.DMLOptions class. This class allows you to specify options for your data manipulation language (DML) operations, such as inserting records.

As an example, let’s say you have a rule to avoid inserting two leads with the same email. You can bypass that rule with the following Apex code:

// Create an instance of Database.DMLOptions
Database.DMLOptions dml = new Database.DMLOptions();

// Set the Duplicate Rule Header options
dml.DuplicateRuleHeader.allowSave = true;
dml.DuplicateRuleHeader.runAsCurrentUser = true;

// Create a new lead with a duplicate email
Lead duplicateLead = new Lead(Email='existing@email.com');

// Insert the lead and pass the DMLOptions
Database.SaveResult sr = Database.insert(duplicateLead, dml);

// Check if the insertion was successful
if (sr.isSuccess()) {
    System.debug('Duplicate lead has been inserted in Salesforce!');
}

By setting dml.DuplicateRuleHeader.allowSave to true, you are overriding the duplicate rule and allowing the record to be saved. Additionally, setting dml.DuplicateRuleHeader.runAsCurrentUser to true ensures that the duplicate rule is evaluated based on the current user’s permissions.

Please note that bypassing duplicate rules should be used with caution and only when necessary. Make sure to carefully consider the implications before implementing this in your code.



About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Join 22 other subscribers

Leave a Reply