SQL Server Primary Key & Unique Constraint Violations: IDENTITY Reseed Drift, Concurrency & Idempotent Ingestion
Root causes behind duplicate key errors during bulk loading and concurrent inserts; DBCC CHECKIDENT diagnostics and atomic SEQUENCE patterns.
Operational Verification & Reliability Metadata
The error string is a symptom, not the root cause. Do not restart the server blindly. Run the diagnostic queries below to pinpoint the actual failure mode.
▸Symptom
Application insert transactions abort with:
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK_Users'. Cannot insert duplicate key in object 'dbo.Users'. The duplicate key value is (1052).
The statement has been terminated.▸What You See in Production
Inserts fail even on auto-incrementing identity columns because the engine generates identity values colliding with existing primary keys.
▸Root Cause Matrix
| Probability | Root Cause | Description |
|---|---|---|
| %50 | IDENTITY Reseed Drift | Following bulk inserts (IDENTITY_INSERT ON) or ungraceful failovers, identity seed lags behind MAX(id). |
| %35 | Concurrent Unique Collision | Interleaved transactions inserting duplicate unique domain keys. |
| %15 | Unprotected MERGE Statements | MERGE statements running without concurrency hints (HOLDLOCK). |
▸EMERGENCY RUNBOOK (0-5 min)
-- 1. Inspect existing duplicate record
SELECT * FROM dbo.Users WHERE id = 1052;
-- 2. Inspect maximum ID versus identity counter
SELECT MAX(id) AS MaxID FROM dbo.Users;
DBCC CHECKIDENT ('dbo.Users', NORESEED);
-- 3. Auto-align identity seed above existing records
DBCC CHECKIDENT ('dbo.Users', RESEED);▸PERMANENT BLUEPRINT
- 1MERGE Concurrency Hardening: Always append
WITH (HOLDLOCK)to target tables in MERGE logic. - 2SEQUENCE Objects: Adopt cached
SEQUENCEstructures for high-throughput tables.
▸Verification
DBCC CHECKIDENT ('dbo.Users', NORESEED);Other Database Error Triage Playbooks
Other battle-tested diagnostic guides for high-severity database errors.
SQL Server Error 18456: Root Cause by State Code Matrix
In Error 18456, the State code reveals the actual root cause. Specific fixes for State 5, 8, 11, 18, 38, and 40, with ERRORLOG extraction scripts.
SQL Server Error 1205 Deadlock: Graph Extraction and Prevention
Extracting the deadlock graph from the system_health Extended Events ring buffer, understanding victim election, and architectural resolution.
SQL Server Pool Timeout: Connection Pool Exhaustion Fix
Difference between connection pool timeout and query command timeout, detecting connection leaks, and .NET DbContext architectural fixes.