SQL Server error 987 ("A duplicate key insert was hit when attempting to insert a new row") means the row you are trying to insert would violate a unique index or primary key constraint. The fix is to find the conflicting row, decide whether the insert should update instead, and then either use an UPDATE, a MERGE, or change the key value. You cannot suppress the error with a query hint; you must resolve the duplicate.

What You'll Need

  • Access to SQL Server Management Studio (SSMS) or Azure Data Studio with permission to read the table and its indexes.
  • The name of the target table and the column(s) that make up the unique key.
  • Permission to run SELECT queries and, if you will fix data, UPDATE or DELETE permission on the table.
  • A backup or a test copy of the database before you change any data.

Step-by-Step

  1. Read the full error message. Error 987 usually names the object and the duplicate key value. Copy that value; you will use it in the next steps. If the message does not show the value, continue to step 2.
  2. Identify the unique constraint. In SSMS, expand the table in Object Explorer, open Indexes, and look for a unique index or the primary key. You can also run: SELECT i.name, i.is_unique, c.name AS column_name FROM sys.indexes i JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id WHERE i.object_id = OBJECT_ID('dbo.YourTable') AND i.is_unique = 1; This lists the columns that must be unique.
  3. Query for the existing row. Run a SELECT with the duplicate value, for example: SELECT * FROM dbo.YourTable WHERE YourKeyColumn = 'the-duplicate-value'; If the table has a composite key, include every key column in the WHERE clause.
  4. Decide the correct outcome. If the existing row should be updated with the new data, use an UPDATE statement. If the new row is genuinely new and the key value is wrong, change the key value in your INSERT. If the existing row is stale, delete it first inside a transaction and then insert.
  5. Use UPDATE when the row already exists. Write an UPDATE that sets the non-key columns to the new values, filtered by the key. Wrap it in a transaction so you can roll back: BEGIN TRANSACTION; UPDATE dbo.YourTable SET Col1 = @Col1 WHERE YourKeyColumn = @Key; COMMIT;
  6. Use MERGE only when you need insert-or-update logic. MERGE can handle both cases in one statement, but test it carefully: a MERGE with a wrong join condition can insert duplicates or update the wrong rows. Always run it inside a transaction and check the affected row count before committing.
  7. Check for race conditions. If error 987 appears intermittently under load, two sessions may be inserting the same key at the same time. Use an application-level lock, a unique index plus retry logic, or an upsert pattern with WITH (UPDLOCK, HOLDLOCK) inside a transaction. Do not rely on checking first and inserting second without a lock.
  8. Verify the fix. Re-run the original INSERT or the application action that failed. Then run a duplicate check: SELECT YourKeyColumn, COUNT(*) FROM dbo.YourTable GROUP BY YourKeyColumn HAVING COUNT(*) > 1; It should return no rows.

Common Mistakes

  • Assuming the error is a bug. Error 987 is the database protecting a unique constraint; the data or the logic is the problem, not SQL Server.
  • Deleting the existing row without checking it. The existing row may be the correct one and your new insert may be wrong. Always SELECT before you DELETE.
  • Ignoring composite keys. If the unique index covers two or more columns, the duplicate is the combination, not a single column. Filtering on one column gives misleading results.
  • Using MERGE without testing. MERGE is convenient but easy to get wrong; a bad join can produce duplicates or update unrelated rows.
  • Forgetting about case and trailing spaces. Depending on the column collation, 'ABC' and 'abc' or 'ABC ' and 'ABC' may be treated as duplicates. Check the collation if the values look different but still conflict.
  • Retrying the same INSERT in a loop. Without changing the key or the logic, the retry will fail every time and can add load to the server.

Tips

  • Always run data-changing statements inside a transaction with a row-count check before COMMIT.
  • Keep a test copy of the database so you can reproduce the error and try the fix safely.
  • Log the duplicate key value in your application so you can trace which code path produced it.
  • If the table is large, index the key column so the duplicate lookup is fast.
  • Review the application logic that generates keys; duplicates often come from retries, imports, or missing sequence values.

Troubleshooting

If the error persists after you fix the obvious duplicate, check these in order. First, confirm you are querying the same table and schema the application writes to; a test database and a production database can look identical but hold different rows. Second, check for triggers on the table that insert into another table with a unique key; the error may come from the trigger, not your statement. Third, look at the full error output in SSMS or the application log; error 987 is sometimes wrapped by a higher-level error that hides the real key value. Fourth, if the error only happens under load, review concurrency: two sessions inserting the same key at the same time need a lock or a retry pattern. Fifth, if you recently changed an index, confirm the unique constraint is still the one you expect. Finally, restore a backup to a test server and reproduce the insert there; if it succeeds on the test copy, the difference is data, permissions, or timing, not the statement itself.

Frequently Asked Questions

What causes SQL Server error 987?

It is raised when an INSERT would create a duplicate value in a column or combination of columns protected by a unique index or primary key constraint.

Can I ignore error 987 and let the insert continue?

No. The insert is rejected to protect the unique constraint. You must change the data, update the existing row, or remove the conflicting row.

Does error 987 mean my database is corrupted?

No. It is a normal constraint violation caused by the data being inserted, not by storage or corruption.

How do I find which row is duplicated?

Use the key value from the error message in a SELECT against the table, or run a GROUP BY with HAVING COUNT(*) > 1 on the key columns to list duplicates.

Should I use MERGE to avoid error 987?

MERGE can handle insert-or-update logic, but it must be written and tested carefully. A simpler UPDATE followed by an INSERT, wrapped in a transaction, is often safer.

Why does the error appear only sometimes?

Intermittent errors usually mean two sessions are inserting the same key at nearly the same time, or an application retry is re-sending the same row. Use locking or retry logic that checks the result before retrying.