Sub topic 7
Duplicate rules and blocking saves
This chapter assumes you can read a simple Apex trigger, know what a validation rule is, and have used insert and update in Apex. It covers where duplicate rules sit in the order of execution and what they do to the transaction.
Where duplicate rules run
Duplicate rules run after your custom validation rules and before the record is written to the database. By this point the before-save flows, before triggers, system validation, and custom validation rules have all passed.
Two consequences follow from this position:
- A before trigger can change the data that matching sees. If a trigger standardizes a phone number or email address, the duplicate rule compares the standardized value.
- A duplicate rule that blocks a save prevents the after triggers from running at all. They never see the record.
Matching rules and duplicate rules
Two pieces of setup work together.
- A matching rule defines what counts as a duplicate. It lists the fields to compare and whether each comparison is exact or fuzzy. Salesforce supplies standard matching rules for objects such as Account, Contact, and Lead.
- A duplicate rule defines what happens when the matching rule finds a match. It names the matching rule, says which records to compare against, and sets the action.
The action is configured separately for creating and for editing a record. There are two choices:
| Action | Behavior in the user interface | Behavior through Apex DML or the API |
|---|---|---|
| Block | The save fails with an error message. | The save fails with a duplicate error. |
| Allow | The user can save. You can choose to show an alert and to report the duplicate. | A save that triggers an alert fails unless the caller opts in to saving. |
Treat the last cell with care. Because there is no person to click "Save anyway", code that hits an Allow rule with an alert needs to say explicitly that saving is acceptable.
Duplicate rules in Apex
An Apex insert or update statement fails when a blocking duplicate rule matches. It throws a DmlException, and the whole statement rolls back. With the Database methods and allOrNone set to false, you get a SaveResult instead and can inspect the errors.
Account acc = new Account(Name = 'Acme Corp', Phone = '555-0100');
Database.SaveResult sr = Database.insert(acc, false);
if (!sr.isSuccess()) {
for (Database.Error err : sr.getErrors()) {
if (err instanceof Database.DuplicateError) {
Database.DuplicateError dupErr = (Database.DuplicateError) err;
Datacloud.DuplicateResult dupResult = dupErr.getDuplicateResult();
System.debug('Rule: ' + dupResult.getDuplicateRule());
System.debug('Blocked: ' + !dupResult.isAllowSave());
for (Datacloud.MatchResult mr : dupResult.getMatchResults()) {
for (Datacloud.MatchRecord rec : mr.getMatchRecords()) {
System.debug('Existing match: ' + rec.getRecord().Id);
}
}
}
}
}Database.DuplicateError is a subclass of Database.Error, so check for it before reading the duplicate details. The Datacloud.DuplicateResult object tells you which rule fired and which existing records matched.
Saving despite a match
When a duplicate is acceptable, for example in a data migration, you can tell Salesforce to allow the save. Set allowSave on the duplicate rule header of a Database.DMLOptions object.
Account acc = new Account(Name = 'Acme Corp', Phone = '555-0100');
Database.DMLOptions dml = new Database.DMLOptions();
dml.DuplicateRuleHeader.allowSave = true;
Database.SaveResult sr = Database.insert(acc, dml);
System.debug('Saved: ' + sr.isSuccess());This option applies to rules whose action is Allow. A rule set to Block still blocks. If you want to bypass a blocking rule, that is a setup decision, not something your code can override.
Edge cases to know
- Batches are not compared with themselves. Matching looks for existing records in the database. Two new records in the same DML call that match each other are generally not flagged against one another. If your integration can send such batches, deduplicate in code first.
- Updates only matter when relevant fields change. An edit that does not touch fields used by the matching rule is unlikely to produce a new duplicate result, but you should not rely on that. Test the edit action if you configured it.
- Rollback is complete. A duplicate error is an error like any other. The transaction rolls back, including work done by before triggers and before-save flows in the same save. Nothing is partially committed.
- Bulk behavior is per record. With
allOrNoneset to false, one duplicate in a list does not stop the others. Each record gets its ownSaveResult.
Design guidance
Put data cleanup that improves matching, such as trimming whitespace or normalizing formats, in a before trigger or before-save flow. Those run before duplicate rules, so the rule sees clean values. Do not try to detect duplicates yourself in an after trigger, because by then a blocking rule has already decided the outcome.
Exercise
A before insert trigger lowercases the Email field on Lead. A duplicate rule with a Block action uses a matching rule that compares Email exactly. A user inserts a Lead with "[email protected]", and "[email protected]" already exists. Is the save blocked? Do the after insert triggers run?
Show answer
The save is blocked. The before trigger runs first and changes the value to "[email protected]", so the matching rule finds an exact match. The block stops the save before the record is written, so the after insert triggers do not run, and the transaction rolls back.
Exercise
You call Database.insert(accounts, false) for 200 accounts, and 3 match existing records under a Block rule. What happens to the other 197, and how do you find the 3?
Show answer
The 197 are saved, because allOrNone is false and each record is handled separately. The 3 get a SaveResult where isSuccess() is false. Their errors include a Database.DuplicateError, which gives you the matching existing records.