Using Duplicate Rules In Apex ~ Salesforce

Hi all,

Salesforce declarative model encompasses duplicate rules, which plays a major role in avoiding duplicate records. However, achieving the same goal in programmatical model can be a bit tricky. Of course we can always go for the brute force method where we can manually compare each field but if we can define duplicate rules and use them in the code, it would be more efficient and maintainable.

In this article, we will be looking at how to access and use duplicate rules in Apex.

For this article, I will be using a sample custom object and apply a duplicate rule as follows:

Duplicate rule

Even though the duplicate rule is configured to “Allow” creation and update, when using Apex code to create a duplicate record, the following error would be thrown.

Error thrown from Apex

In order to handle this kind of errors during Apex code execution (because we wouldn’t want these errors shown to customers, do we?), the following two methods can be used.

1. Insert and capture the error:

The duplicate rule can be captured by the errors thrown at insertion as follows:

2. Find if duplicates exist before insertion:

If you want to check for duplicates before trying to insert, that too can be done using the FindDuplicates class in Datacloud namespace.

And that’s how to avoid errors when using duplicate rules in Salesforce. Hope you learned something today!

Cheers!

Resources:

  1. Datacloud Namespace
  2. FindDuplicates class

--

--