ERROR: duplicate key value violates unique constraint - 10 Causes and Fixes in Postgres

You ran an INSERT and Postgres answered with ERROR: duplicate key value violates unique constraint. The detail line underneath it names the column and the value: DETAIL: Key (email)=(ada@example.com) already exists.

That message means exactly one thing: the row you tried to write would have made two rows share a value in a column (or set of columns) that is declared UNIQUE or is the PRIMARY KEY. Postgres refuses the write and rolls back the statement rather than let the duplicate land.

The interesting part is never the constraint — it is why your code produced a value that already exists. That ranges from an out-of-sync sequence after a data import, to a race between two concurrent requests, to a UNIQUE index that is case-sensitive when your users are not.

This page walks the ten causes that account for nearly every occurrence, each with a reproduction you can paste into psql and the fix that differs from it by the lines that matter. Eyeglasses reflecting computer code on a monitor, ideal for technology and programming themes.

ErrorERROR: duplicate key value violates unique constraint "users_email_key" DETAIL: Key (email)=(ada@example.com) already exists.
Where it happensPostgreSQL (all supported versions), raised by the server. Surfaces through any client or ORM: psql, psycopg, node-postgres, Prisma, SQLAlchemy, Rails ActiveRecord, JDBC. SQLSTATE 23505 (unique_violation).
What it meansPostgres is telling you the row you tried to insert or update would duplicate a value in a column that you promised would be unique.

The Fast Fix

Read the DETAIL: line first — it names the exact column and value that collided. That tells you whether the duplicate is real data or a generated id.

If the colliding column is a serial/identity primary key, your sequence is behind the table (classic after a COPY or dump restore that wrote explicit ids). Resync it:

SELECT setval(
  pg_get_serial_sequence('users', 'id'),
  COALESCE((SELECT MAX(id) FROM users), 0) + 1,
  false
);

If the colliding column is real business data (email, slug, external id), the insert itself is wrong — make it idempotent with ON CONFLICT instead of retrying blindly:

INSERT INTO users (email, name) VALUES ('ada@example.com', 'Ada')
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;

If neither applies, work the diagnostic checklist below.

What Is Actually Causing It

1. Sequence is behind the table after a data import

Reproduce it

CREATE TABLE users (id serial PRIMARY KEY, email text);

-- Bulk load with explicit ids: the sequence is never advanced
INSERT INTO users (id, email) VALUES (1, 'a@example.com'), (2, 'b@example.com');

-- The app inserts without an id and the sequence hands out 1
INSERT INTO users (email) VALUES ('c@example.com');
-- ERROR: duplicate key value violates unique constraint "users_pkey"
-- DETAIL: Key (id)=(1) already exists.

Why it happens — A serial column's default is nextval() on a sequence, and the sequence is only advanced when the default actually fires. Supplying id explicitly — which every pg_dump restore and COPY of existing data does — bypasses the default, so the sequence still sits at 1 while the table already holds ids 1 and 2.

The fix

SELECT setval(
  pg_get_serial_sequence('users', 'id'),
  COALESCE((SELECT MAX(id) FROM users), 0) + 1,
  false
);

INSERT INTO users (email) VALUES ('c@example.com'); -- now gets id 3

What changed: the sequence is moved past the highest existing id. The false third argument means "this value has not been used yet", so the next nextval() returns it rather than skipping it.

Confirm it worked — Run SELECT last_value FROM users_id_seq; (or SELECT currval(pg_get_serial_sequence('users','id'))) and confirm it is greater than SELECT MAX(id) FROM users. Then insert one row without an id and watch it succeed.


2. Insert should have been an upsert

Reproduce it

CREATE TABLE settings (user_id int PRIMARY KEY, theme text);
INSERT INTO settings (user_id, theme) VALUES (7, 'dark');

-- Second save of the same form
INSERT INTO settings (user_id, theme) VALUES (7, 'light');
-- ERROR: duplicate key value violates unique constraint "settings_pkey"

Why it happens — The code treats "save" as "create", so the second write of the same logical record collides with the first. Any endpoint a user can submit twice, or a job that can be retried, needs insert-or-update semantics rather than plain insert.

The fix

INSERT INTO settings (user_id, theme) VALUES (7, 'light')
ON CONFLICT (user_id) DO UPDATE SET theme = EXCLUDED.theme;

What changed: ON CONFLICT (user_id) DO UPDATE turns the statement into an upsert. EXCLUDED refers to the row you tried to insert, so the update applies the new value. Use DO NOTHING instead when a second write should be ignored.

Confirm it worked — Run the same statement twice in a row. Both should report INSERT 0 1 with no error, and SELECT theme FROM settings WHERE user_id = 7 should return the latest value.


3. Concurrent requests both pass a check-then-insert

Reproduce it

# Two workers run this at the same moment
cur.execute("SELECT 1 FROM users WHERE email = %s", (email,))
if cur.fetchone() is None:
    cur.execute("INSERT INTO users (email) VALUES (%s)", (email,))
# One worker wins; the other raises
# UniqueViolation: duplicate key value violates unique constraint "users_email_key"

Why it happens — The SELECT and the INSERT are two separate statements, so nothing stops a second transaction from inserting the same email in the gap between them. Under the default READ COMMITTED isolation level, neither transaction sees the other's uncommitted row, so both pass the existence check.

The fix

# Let the database arbitrate instead of the application
cur.execute(
    "INSERT INTO users (email) VALUES (%s) ON CONFLICT (email) DO NOTHING RETURNING id",
    (email,),
)
row = cur.fetchone()
if row is None:
    cur.execute("SELECT id FROM users WHERE email = %s", (email,))
    row = cur.fetchone()

What changed: the check and the write became one atomic statement. DO NOTHING returns no row when the insert was skipped, which is how you detect the loser and read the winner's id.

Confirm it worked — Hammer the endpoint with concurrent requests for the same email (ab, hey, or a loop of parallel psql calls) and confirm zero 23505 errors in the Postgres log while SELECT count(*) FROM users WHERE email = ... stays at 1.


4. The unique index is case-sensitive but your data is not

Reproduce it

CREATE TABLE users (id serial PRIMARY KEY, email text UNIQUE);
INSERT INTO users (email) VALUES ('Ada@Example.com'); -- accepted
INSERT INTO users (email) VALUES ('ada@example.com'); -- accepted too

-- Later you add the index you actually wanted
CREATE UNIQUE INDEX users_email_lower_idx ON users (lower(email));
-- ERROR: could not create unique index "users_email_lower_idx"
-- DETAIL: Key (lower(email))=(ada@example.com) is duplicated.

Why it happens — text comparison in Postgres is case-sensitive under the default collation, so Ada@Example.com and ada@example.com are two distinct values to a plain UNIQUE constraint. The duplicate only surfaces the moment you try to enforce case-insensitive uniqueness — or when a user cannot log in because there are two of them.

The fix

-- 1. Collapse the existing duplicates (keep the lowest id)
DELETE FROM users a
USING users b
WHERE lower(a.email) = lower(b.email) AND a.id > b.id;

-- 2. Normalise on write and enforce on the normalised value
UPDATE users SET email = lower(email);
CREATE UNIQUE INDEX users_email_lower_idx ON users (lower(email));

What changed: uniqueness is now enforced on lower(email) rather than the raw string. Match it in queries with WHERE lower(email) = lower($1) so the index is used.

Confirm it worked — INSERT INTO users (email) VALUES ('ADA@EXAMPLE.COM'); must now fail with a unique violation, and SELECT lower(email), count(*) FROM users GROUP BY 1 HAVING count(*) > 1; must return zero rows.


5. Retried request or double-clicked form submits twice

Reproduce it

# Client timed out and the HTTP layer retried; the first request had already committed
curl -X POST /orders -d '{"sku":"ABC","qty":1}'  # succeeded, response lost
curl -X POST /orders -d '{"sku":"ABC","qty":1}'  # retry
# 500 duplicate key value violates unique constraint "orders_idem_key"

Why it happens — At-least-once delivery is the norm for HTTP clients, load balancers, and message queues. If the write is not idempotent, the second delivery of the same logical operation collides with the row the first one already committed.

The fix

-- Give the operation a client-supplied idempotency key
ALTER TABLE orders ADD COLUMN idempotency_key text;
CREATE UNIQUE INDEX orders_idem_key ON orders (idempotency_key);
INSERT INTO orders (idempotency_key, sku, qty)
VALUES ($1, 'ABC', 1)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id;

What changed: the retry now hits DO NOTHING instead of a violation. When RETURNING yields no row, look up the original order by its key and return that — the retry becomes a no-op with the same response.

Confirm it worked — Send the identical request twice with the same idempotency key. Both should return HTTP 2xx with the same order id, and SELECT count(*) FROM orders WHERE idempotency_key = $1 should be 1.


6. Multi-column unique constraint, and you only checked one column

Reproduce it

CREATE TABLE memberships (
  user_id int,
  team_id int,
  role text,
  UNIQUE (user_id, team_id)
);
INSERT INTO memberships VALUES (1, 10, 'member');

-- Application checks "is this user already a member of any team?" -> no match logic bug
INSERT INTO memberships VALUES (1, 10, 'admin');
-- ERROR: duplicate key value violates unique constraint "memberships_user_id_team_id_key"
-- DETAIL: Key (user_id, team_id)=(1, 10) already exists.

Why it happens — A composite UNIQUE constraint is violated only when every column in the tuple matches an existing row. Code that guards on a single column (or that assumes the role column is part of the key) will happily produce a colliding tuple.

The fix

INSERT INTO memberships (user_id, team_id, role)
VALUES (1, 10, 'admin')
ON CONFLICT (user_id, team_id) DO UPDATE SET role = EXCLUDED.role;

What changed: the conflict target lists the full composite key, which is what Postgres requires to match the constraint, and a role change now updates the existing membership instead of trying to create a second one.

Confirm it worked — Read the constraint definition with \d memberships in psql (or SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conname = 'memberships_user_id_team_id_key';) and confirm your conflict target and your application-level check both cover exactly those columns.


More causes (5 remaining)

7. Two writers share one sequence range or hardcode ids

Reproduce it

CREATE TABLE events (id bigint PRIMARY KEY, payload jsonb);

-- Worker A computes the next id itself
INSERT INTO events (id, payload)
SELECT COALESCE(MAX(id), 0) + 1, '{}'::jsonb FROM events;

-- Worker B does the same thing concurrently with the same MAX
-- ERROR: duplicate key value violates unique constraint "events_pkey"

Why it happens — MAX(id) + 1 is a read followed by a write, so two concurrent transactions compute the same next id. Sequences exist precisely because they hand out values outside transactional visibility — no two callers ever get the same number, even on rollback.

The fix

ALTER TABLE events ALTER COLUMN id SET NOT NULL;
CREATE SEQUENCE events_id_seq OWNED BY events.id;
SELECT setval('events_id_seq', COALESCE((SELECT MAX(id) FROM events), 0) + 1, false);
ALTER TABLE events ALTER COLUMN id SET DEFAULT nextval('events_id_seq');

INSERT INTO events (payload) VALUES ('{}'::jsonb); -- id comes from the sequence

What changed: id generation moved from application arithmetic to a sequence default. Stop passing id from the client entirely. If you need ids generated outside the database, use gen_random_uuid() and a uuid column instead.

Confirm it worked — Run two concurrent insert loops for a few thousand rows each. There should be no unique violations, and SELECT count(*), count(DISTINCT id) FROM events should return equal numbers.


8. ORM thinks the entity is new when it already exists

Reproduce it

# SQLAlchemy: a detached object re-added to a session
user = User(id=42, email='ada@example.com')  # id set by hand
session.add(user)
session.commit()
# IntegrityError: duplicate key value violates unique constraint "users_pkey"

Why it happens — An ORM decides between INSERT and UPDATE from the object's persistence state, not from what is in the table. A hand-constructed instance, a detached object re-added after a session closed, or an object rebuilt from a serialised payload all look brand new, so the ORM emits an INSERT for a primary key that already exists.

The fix

# Load the row into the session, then mutate it
user = session.get(User, 42)
if user is None:
    user = User(email='ada@example.com')
    session.add(user)
else:
    user.email = 'ada@example.com'
session.commit()

What changed: the object is fetched into the session first, so the ORM emits an UPDATE for the existing row. session.merge(obj) achieves the same thing in one call when you already hold a detached instance.

Confirm it worked — Turn on statement logging for the unit of work (echo=True in SQLAlchemy, log: ['query'] in Prisma, or log_statement = 'all' in Postgres) and confirm the emitted SQL is UPDATE, not INSERT.


9. NULLs behave differently than you expect in a unique index

Reproduce it

CREATE TABLE docs (id serial PRIMARY KEY, owner_id int, slug text, UNIQUE (owner_id, slug));
INSERT INTO docs (owner_id, slug) VALUES (NULL, 'draft');
INSERT INTO docs (owner_id, slug) VALUES (NULL, 'draft'); -- accepted! no error

-- Then you backfill owner_id and the real duplicate appears
UPDATE docs SET owner_id = 1 WHERE owner_id IS NULL;
-- ERROR: duplicate key value violates unique constraint "docs_owner_id_slug_key"
-- DETAIL: Key (owner_id, slug)=(1, draft) already exists.

Why it happens — By default a unique index treats NULL values as distinct, so any number of rows with a NULL in the key can coexist. The constraint is not enforced on those rows at all — the duplicate stays hidden until an UPDATE replaces the NULL with a real value and the tuples finally collide.

The fix

-- Deduplicate before the backfill
DELETE FROM docs a USING docs b
WHERE a.slug = b.slug
  AND a.owner_id IS NULL AND b.owner_id IS NULL
  AND a.id > b.id;

-- Then make the column mandatory so NULLs cannot reopen the hole
UPDATE docs SET owner_id = 1 WHERE owner_id IS NULL;
ALTER TABLE docs ALTER COLUMN owner_id SET NOT NULL;

What changed: the hidden duplicates are removed before the backfill, and NOT NULL stops the key column from ever being exempt again. On PostgreSQL 15 and later you can instead declare UNIQUE NULLS NOT DISTINCT (owner_id, slug) to have NULLs collide like any other value.

Confirm it worked — Before the backfill, run SELECT owner_id, slug, count(*) FROM docs GROUP BY 1, 2 HAVING count(*) > 1; — and also check for NULL-key groups with SELECT slug, count(*) FROM docs WHERE owner_id IS NULL GROUP BY 1 HAVING count(*) > 1;. Both must be empty.


10. Multi-row INSERT contains the duplicate inside itself

Reproduce it

CREATE TABLE tags (name text PRIMARY KEY);

INSERT INTO tags (name) VALUES ('sql'), ('postgres'), ('sql');
-- ERROR: duplicate key value violates unique constraint "tags_pkey"
-- DETAIL: Key (name)=(sql) already exists.

Why it happens — The duplicate is in the batch, not in the table — the table may be empty. ON CONFLICT does not save you here either: Postgres cannot update a row twice in the same command, so a batch with internal duplicates raises ON CONFLICT DO UPDATE command cannot affect row a second time.

The fix

-- Deduplicate the batch before it reaches the table
INSERT INTO tags (name)
SELECT DISTINCT name FROM (VALUES ('sql'), ('postgres'), ('sql')) AS v(name)
ON CONFLICT (name) DO NOTHING;

What changed: SELECT DISTINCT collapses the in-batch duplicates, and ON CONFLICT DO NOTHING absorbs collisions with rows that are already stored. For composite keys use DISTINCT ON (col1, col2) with an ORDER BY that picks the winner you want.

Confirm it worked — Run the statement against a table that already holds 'sql'. It should report INSERT 0 1 with no error, and SELECT count(*) FROM tags WHERE name = 'sql' should be 1.


11. Partitioned or sharded tables with per-partition sequences

Reproduce it

CREATE TABLE logs (id bigint, created_at date) PARTITION BY RANGE (created_at);
CREATE TABLE logs_2026_01 PARTITION OF logs
  FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');

-- A separate sequence per shard, both starting at 1
INSERT INTO logs_2026_01 (id, created_at) VALUES (1, '2026-01-05');
-- A second region replays its own id 1 into the same partition
INSERT INTO logs_2026_01 (id, created_at) VALUES (1, '2026-01-06');
-- ERROR: duplicate key value violates unique constraint "logs_2026_01_pkey"

Why it happens — Each shard or region generating ids from its own sequence produces overlapping ranges. The collision only appears when those rows land in the same physical table — during consolidation, replication into a central warehouse, or a backfill.

The fix

-- Option A: non-overlapping ranges per writer
CREATE SEQUENCE logs_id_seq_region_b START 1000000000 INCREMENT 1;

-- Option B: globally unique ids, no coordination needed
ALTER TABLE logs ALTER COLUMN id TYPE uuid USING gen_random_uuid();
ALTER TABLE logs ALTER COLUMN id SET DEFAULT gen_random_uuid();

What changed: either the writers are given disjoint id ranges, or id generation stops needing coordination at all. gen_random_uuid() is built in from PostgreSQL 13 onward; on older versions enable pgcrypto first.

Confirm it worked — Across all writers, run SELECT id, count(*) FROM logs GROUP BY id HAVING count(*) > 1; after a consolidation run — it must be empty. For the range approach, confirm each sequence's min_value/start_value via \dS+ logs_id_seq_region_b.

Close-up view of modern rack-mounted server units in a data center. ## None of Those? Narrow It Down
  1. Read the full error, not just the first line. The DETAIL: Key (col)=(value) already exists. line names the column and the colliding value. If the column is an id, suspect a sequence or id-generation problem; if it is business data, suspect application logic.
  2. Get the real constraint definition: SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conname = '<name from the error>';. This tells you whether the key is single-column, composite, or an expression index — and whether your application-level check covers the same columns.
  3. Ask whether the colliding value already exists in the table: SELECT * FROM <table> WHERE <col> = '<value from DETAIL>';. A row comes back means the duplicate is real data and the insert should have been an upsert. No row comes back means the duplicate is inside your own batch or another uncommitted transaction.
  4. If the key is a serial/identity column, compare the sequence to the table: SELECT last_value FROM <seq>; against SELECT MAX(id) FROM <table>;. The sequence lagging behind the max confirms an import or an explicit-id insert broke it.
  5. Check whether the failure is intermittent under load. Reproducible on every attempt points at logic or sequence state; only under concurrency points at check-then-insert racing, which no amount of retrying fixes.
  6. Look for hidden duplicates the constraint is not enforcing: SELECT <key cols>, count(*) FROM <table> GROUP BY 1 HAVING count(*) > 1; plus a NULL-specific variant. Rows with NULL in the key escape a default unique index entirely and surface later during a backfill.
  7. Normalise and re-check for near-duplicates: SELECT lower(trim(<col>)), count(*) FROM <table> GROUP BY 1 HAVING count(*) > 1;. Hits here mean your uniqueness rule and your users' idea of "the same value" disagree on case or whitespace.
  8. Turn on statement logging (SET log_statement = 'all'; for the session, or your ORM's query log) and read the SQL actually sent. An INSERT where you expected an UPDATE points at ORM persistence state rather than the database.

Why This Error Exists At All

A UNIQUE constraint is not a validation rule that Postgres runs on your behalf — it is a physical index with an enforcement flag. When you declare UNIQUE (email), Postgres creates a B-tree index on email and refuses any insert that would place a second entry under an existing key. That is why the error names an index (users_email_key), not a table or a column: the failure happens inside the index, at the moment of the write.

This design is deliberate, and it is the reason the constraint is trustworthy. The check and the write are the same operation, holding the same lock on the same index page, so there is no window between "is this value free?" and "claim this value". No application can get that guarantee, because any application-level check is a separate round trip with a gap in the middle — which is exactly cause #3 on this page. Postgres is offering to be the single serialisation point for a uniqueness decision, and a 23505 error is it doing its job.

The same design explains the behaviours that feel like bugs. Sequences are non-transactional on purpose: nextval() must never block or roll back, otherwise every concurrent insert would queue behind one id counter. The cost is that explicit-id inserts silently leave the sequence behind, which is why restores break it. NULLs are distinct by default because SQL treats NULL = NULL as unknown, not true, and a unique index honours that comparison semantics rather than inventing an exception. And a unique index enforces equality under the column's collation, which is case-sensitive for text — so uniqueness means byte equality unless you index an expression like lower(email) instead.

Once you see the constraint as an index entry being claimed, the whole family of these errors reads the same way: something generated a key that was already claimed, and the only questions are who generated it and whether the claim was visible at the time. Foreign key violations, exclusion constraint violations, and could not create unique index on a CREATE INDEX are all the same mechanism reporting from a different angle. Software developer analyzing code on a tablet in a modern office workspace.

Stop It From Coming Back

  • Make every write that a client can retry idempotent: either ON CONFLICT (cols) DO UPDATE/DO NOTHING, or a client-supplied idempotency key column with its own unique index. Never pair a SELECT existence check with a separate INSERT.
  • Never pass id from application code for sequence-backed columns. Prefer GENERATED BY DEFAULT AS IDENTITY over serial — it makes explicit-id inserts an opt-in (OVERRIDING SYSTEM VALUE) instead of the silent default, which is what breaks sequences.
  • Add a post-restore step to your deploy and migration scripts that resyncs every sequence with setval(pg_get_serial_sequence(table, col), COALESCE(MAX(col),0)+1, false). Run it after any pg_restore or COPY that carried explicit ids.
  • Enforce uniqueness on the normalised value, not the raw string: CREATE UNIQUE INDEX ... ON users (lower(email)) for anything users type, and normalise on write so queries match the index.
  • Declare key columns NOT NULL, or use UNIQUE NULLS NOT DISTINCT on PostgreSQL 15+, so nullable key columns cannot accumulate invisible duplicates that detonate during a later backfill.
  • Catch SQLSTATE 23505 specifically in your error handling (psycopg.errors.UniqueViolation, err.code === '23505' in node-postgres) and return a 409 with a useful message, rather than letting it become a 500. Add a concurrency test that fires the same create request in parallel and asserts exactly one row.
  • Deduplicate batches in the query itself with SELECT DISTINCT or DISTINCT ON (key cols) before they hit a table, since ON CONFLICT DO UPDATE cannot handle a key appearing twice in one command.

Related Guides

Errors You Will Probably Hit Next

  • ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
  • ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
  • ERROR: could not create unique index "..." DETAIL: Key (...)=(...) is duplicated.
  • ERROR: insert or update on table "..." violates foreign key constraint "..."

The constraint is almost never the problem — read the DETAIL: line, decide whether the colliding value is a generated id or real data, and the cause narrows to two or three candidates immediately. Generated id means the sequence or your id generation is wrong; real data means the write should have been an upsert. If it only fails under load, stop looking at the data and look for a check-then-insert gap, because that one is a design flaw and retries will not close it.

댓글

이 블로그의 인기 게시물

TypeError: Cannot read properties of undefined (reading 'map') - 11 Causes and Fixes

psql: FATAL: password authentication failed for user - 10 Causes and Fixes

Error: ERR_MODULE_NOT_FOUND: Cannot find package - 10 Causes and Fixes