Dynamics CRM, Performance

Alternate Keys helps preventing duplicates

If you want to prevent duplicates in CRM, you can use duplicate detection rules. This will inform the users, that there is a duplicate, but it’s just an information. The user can click save and the duplicate will be created.

If you use the SDK, you won’t get an information about duplicates automatically. Only if you call the RetrieveDuplicatesRequest, to check for duplicates.

There are two options, which might help:

  1. You can create a plugin, which checks on each create or update, if there is a duplicate and then throwing an exception.
  2. You can use alternate keys.

 

Let’s explain this on an example:

 

You create accounts, which are having an account number. An account number has to be unique and mustn’t be duplicates. To prevent, that there is an account created with the same account number, we will create an alternate key.

 

To create an alternate key navigate to settings > customizations > customize the system. Expand the account entity and you will find a section called Keys.

Alternate Keys in accounts

Click on the New-Button, add a Name for the key and select the fields you want to use for the key and click ok.

Adding a new alternate key

The key will be created and if everything is correct, the status will switch from pending (during the first check and the creation) to active.

Active alternate key

If there was an error during the creation, you can get the error details via the link to the system job.

 

Now you have a key, which prevents duplicates, but also an additional feature. You got an index on these fields.

This means, if you search for these fields, your results will be delivered faster by the database, as the database can use the automatically created index. You can find the index in your database like on the screenshot below.

Create index of the alternate key

 

If we are creating an entry which violates this key, we are getting an error message:

Trying to add a duplicate

 

This message provides all needed information:

  1. It’s a duplicate
  2. The alternate key, which is preventing the saving is named in the message.

 

 

But there are also some limitation (additional information can be found here):

  1. Only attributes of the following types can be included in alternate key definitions:
    1. Decimal Number
    2. Whole Number
    3. Single line of text
  2. When a key is created, the system validates that the key can be supported by the platform, including that the total key size does not violate SQL-based index constraints like 900 bytes per key and 16 columns per key. If the key size doesn’t meet the constraints, an error message will be displayed.
  3. There can be a maximum of 5 alternate key definitions for an entity in a Dynamics 365 instance.