Skip to Content

Prevent Duplicate Records

Check for existing records and prevent duplicates based on specific field combinations.

Table: incident When: before
#duplicate-prevention #validation #before #insert #data-quality

Script Code

JavaScript
1(function executeRule(current, previous /*null when async*/) {
2
3  // Only check on insert
4  if (!current.isNewRecord()) {
5    return;
6  }
7
8  // Configuration: Define fields to check for duplicates
9  var fieldsToCheck = {
10    'caller_id': current.caller_id.toString(),
11    'short_description': current.short_description.toString(),
12    'category': current.category.toString()
13  };
14
15  // Optional: Time window to check (in hours)
16  var timeWindowHours = 24;
17
18  // Build the duplicate check query
19  var grDuplicate = new GlideRecord('incident');
20
21  // Add field conditions
22  for (var field in fieldsToCheck) {
23    var value = fieldsToCheck[field];
24    if (value) {
25      grDuplicate.addQuery(field, value);
26    }
27  }
28
29  // Only check recent records (optional)
30  var gdt = new GlideDateTime();
31  gdt.addHours(-timeWindowHours);
32  grDuplicate.addQuery('sys_created_on', '>', gdt);
33
34  // Exclude current record if it has a sys_id
35  if (current.sys_id) {
36    grDuplicate.addQuery('sys_id', '!=', current.sys_id);
37  }
38
39  // Only check open incidents
40  grDuplicate.addQuery('active', 'true');
41
42  grDuplicate.setLimit(1);
43  grDuplicate.query();
44
45  // If duplicate found, prevent insert
46  if (grDuplicate.next()) {
47    var errorMsg = 'A similar incident already exists: ' + grDuplicate.number + '. ';
48    errorMsg += 'Please check existing incidents before creating a new one.';
49
50    gs.addErrorMessage(errorMsg);
51    current.setAbortAction(true);
52
53    gs.warn('Duplicate incident prevented for caller: ' + current.caller_id.getDisplayValue() +
54            ', existing: ' + grDuplicate.number);
55  }
56
57})(current, previous);

How to Use

1. Create a before Business Rule on your table 2. Check "Insert" checkbox only 3. Customize `fieldsToCheck` for your duplicate detection logic 4. Decide between hard prevention or soft warning 5. Test by creating duplicate records

Explore More Scripts

Browse our complete library of ServiceNow scripts

View All Scripts