← Script library

Business Rules

Prevent Duplicate Records

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

JavaScript
(function executeRule(current, previous /*null when async*/) {

  // Only check on insert
  if (!current.isNewRecord()) {
    return;
  }

  // Configuration: Define fields to check for duplicates
  var fieldsToCheck = {
    'caller_id': current.caller_id.toString(),
    'short_description': current.short_description.toString(),
    'category': current.category.toString()
  };

  // Optional: Time window to check (in hours)
  var timeWindowHours = 24;

  // Build the duplicate check query
  var grDuplicate = new GlideRecord('incident');

  // Add field conditions
  for (var field in fieldsToCheck) {
    var value = fieldsToCheck[field];
    if (value) {
      grDuplicate.addQuery(field, value);
    }
  }

  // Only check recent records (optional)
  var gdt = new GlideDateTime();
  gdt.addHours(-timeWindowHours);
  grDuplicate.addQuery('sys_created_on', '>', gdt);

  // Exclude current record if it has a sys_id
  if (current.sys_id) {
    grDuplicate.addQuery('sys_id', '!=', current.sys_id);
  }

  // Only check open incidents
  grDuplicate.addQuery('active', 'true');

  grDuplicate.setLimit(1);
  grDuplicate.query();

  // If duplicate found, prevent insert
  if (grDuplicate.next()) {
    var errorMsg = 'A similar incident already exists: ' + grDuplicate.number + '. ';
    errorMsg += 'Please check existing incidents before creating a new one.';

    gs.addErrorMessage(errorMsg);
    current.setAbortAction(true);

    gs.warn('Duplicate incident prevented for caller: ' + current.caller_id.getDisplayValue() +
            ', existing: ' + grDuplicate.number);
  }

})(current, previous);

How to use it

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

Adapt the table names, fields, and conditions to your instance. Test the behavior in a development environment before using it in production.