PostgreSQL 17.12Lab-verified · 2026-12-01

PostgreSQL error 23505: duplicate key value violates unique constraint

The row you inserted has the same value as an existing row in a primary key or unique column.

PostgreSQL 17.12
23505: duplicate key value violates unique constraint "members_email_key"

Jump to a cause

  1. 01The value already exists in a unique column
  2. 02The serial / identity sequence is behind ids that were inserted manually
  3. 03The insert should update the row when the key already exists
  4. 04A unique index on lower(email) — values that differ only in case
  5. 05A partial unique index (WHERE is_default) — "only one default address"
  6. 06An UPDATE that shifts a UNIQUE column by +1 (reordering)

Lab-verifiedReproduced and fixed on PostgreSQL 17.12 · 2026-12-01 · container image postgres:17

23505 means a primary key or UNIQUE constraint rejected the row. The DETAIL line tells you exactly which column and value collided, for example Key (email)=(kim@example.com) already exists.

Read that line first. If the value really exists, it is a data problem. If the value is an id you never typed yourself (like Key (id)=(1)), the sequence behind the column is usually out of sync.

01The value already exists in a unique column

email has a UNIQUE constraint, and kim@example.com is already stored for id 1. Inserting a second row with the same email fails, and the constraint name members_email_key tells you which rule was hit. Look up the existing row with the value from DETAIL, then insert a different value or update the existing row.

Setup
Setuprun as lab_a
CREATE TABLE members (id int PRIMARY KEY, email text UNIQUE, name text);
INSERT INTO members VALUES (1, 'kim@example.com', 'Kim');
OUTPUT
CREATE TABLE
INSERT 0 1
Reproducerun as lab_a
INSERT INTO members VALUES (2, 'kim@example.com', 'Kim2');
✕ ERROR
ERROR:  23505: duplicate key value violates unique constraint "members_email_key"
DETAIL:  Key (email)=(kim@example.com) already exists.
SCHEMA NAME:  lab_a
TABLE NAME:  members
CONSTRAINT NAME:  members_email_key
Checkrun as lab_a
SELECT id, email, name FROM members WHERE email = 'kim@example.com';
OUTPUT
 id |      email      | name
----+-----------------+------
  1 | kim@example.com | Kim
(1 row)
After the fixrun as lab_a
INSERT INTO members VALUES (2, 'lee@example.com', 'Lee');
SELECT id, email FROM members ORDER BY id;
✓ SUCCESS
INSERT 0 1
 id |      email
----+-----------------
  1 | kim@example.com
  2 | lee@example.com
(2 rows)

02The serial / identity sequence is behind ids that were inserted manually

Rows 1 to 10 were migrated with their ids written explicitly, so the serial sequence was never advanced. The next INSERT without an id takes nextval = 1, which already exists. The check shows the table maximum is 10 while the sequence is only at 4 (failed inserts still consume sequence numbers, they are not rolled back).

Setup
Setuprun as lab_a
CREATE TABLE orders (id serial PRIMARY KEY, item text);
-- migrated rows keep their old ids
INSERT INTO orders (id, item) SELECT g, 'imported-' || g FROM generate_series(1, 10) g;
OUTPUT
CREATE TABLE
INSERT 0 10
Reproducerun as lab_a
INSERT INTO orders (item) VALUES ('new');
✕ ERROR
ERROR:  23505: duplicate key value violates unique constraint "orders_pkey"
DETAIL:  Key (id)=(1) already exists.
SCHEMA NAME:  lab_a
TABLE NAME:  orders
CONSTRAINT NAME:  orders_pkey
Checkrun as lab_a
SELECT max(id) AS max_id, (SELECT last_value FROM orders_id_seq) AS seq_last FROM orders;
OUTPUT
 max_id | seq_last
--------+----------
     10 |        4
(1 row)
Fixrun as lab_a
SELECT setval(pg_get_serial_sequence('orders', 'id'), (SELECT max(id) FROM orders));
OUTPUT
 setval
--------
     10
(1 row)

setval(pg_get_serial_sequence('orders', 'id'), (SELECT max(id) FROM orders)) moves the sequence to the current maximum, so the next insert gets 11. Run it after every bulk load or restore that writes ids directly.

After the fixrun as lab_a
INSERT INTO orders (item) VALUES ('new') RETURNING id;
✓ SUCCESS
 id
----
 11
(1 row)

INSERT 0 1

03The insert should update the row when the key already exists

Sync jobs often send rows that may or may not exist yet. A-100 is already stored with quantity 5, so a plain INSERT fails. INSERT … ON CONFLICT (sku) DO UPDATE SET qty = EXCLUDED.qty inserts new keys and updates existing ones in one statement; here the quantity became 7.

Setup
Setuprun as lab_a
CREATE TABLE stock (sku text PRIMARY KEY, qty int NOT NULL);
INSERT INTO stock VALUES ('A-100', 5);
OUTPUT
CREATE TABLE
INSERT 0 1
Reproducerun as lab_a
INSERT INTO stock VALUES ('A-100', 7);
✕ ERROR
ERROR:  23505: duplicate key value violates unique constraint "stock_pkey"
DETAIL:  Key (sku)=(A-100) already exists.
SCHEMA NAME:  lab_a
TABLE NAME:  stock
CONSTRAINT NAME:  stock_pkey
Checkrun as lab_a
SELECT * FROM stock WHERE sku = 'A-100';
OUTPUT
  sku  | qty
-------+-----
 A-100 |   5
(1 row)
After the fixrun as lab_a
INSERT INTO stock VALUES ('A-100', 7)
ON CONFLICT (sku) DO UPDATE SET qty = EXCLUDED.qty;
SELECT * FROM stock;
✓ SUCCESS
INSERT 0 1
  sku  | qty
-------+-----
 A-100 |   7
(1 row)

04A unique index on lower(email) — values that differ only in case

members already has kim@example.com, and the new value is Kim@Example.com. The text differs, but the unique index is on lower(email), so the insert failed. When DETAIL shows an expression such as Key (lower(email))=(kim@example.com) instead of a column, this is the case.

Setup
Setuprun as lab_a
CREATE TABLE members (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL);
CREATE UNIQUE INDEX members_email_lower_uq ON members (lower(email));
INSERT INTO members (email) VALUES ('kim@example.com');
OUTPUT
CREATE TABLE
CREATE INDEX
INSERT 0 1
Reproducerun as lab_a
INSERT INTO members (email) VALUES ('Kim@Example.com');
✕ ERROR
ERROR:  23505: duplicate key value violates unique constraint "members_email_lower_uq"
DETAIL:  Key (lower(email))=(kim@example.com) already exists.
SCHEMA NAME:  lab_a
TABLE NAME:  members
CONSTRAINT NAME:  members_email_lower_uq
Check the causerun as lab_a
SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'members' ORDER BY indexname;
SELECT id, email FROM members WHERE lower(email) = lower('Kim@Example.com');
OUTPUT
       indexname        |                                        indexdef
------------------------+----------------------------------------------------------------------------------------
 members_email_lower_uq | CREATE UNIQUE INDEX members_email_lower_uq ON lab_a.members USING btree (lower(email))
 members_pkey           | CREATE UNIQUE INDEX members_pkey ON lab_a.members USING btree (id)
(2 rows)

 id |      email
----+-----------------
  1 | kim@example.com
(1 row)

indexdef shows (lower(email)), and searching with lower() finds row 1, kim@example.com. It is the same person.

Checkrun as lab_a
SELECT id, email FROM members WHERE lower(email) = lower('Kim@Example.com');
OUTPUT
 id |      email
----+-----------------
  1 | kim@example.com
(1 row)

Since it is the same person, nothing new was inserted. ON CONFLICT (lower(email)) DO NOTHING returned INSERT 0 0 without an error and the table still has one row. With an expression index, ON CONFLICT needs the same expression.

After the fixrun as lab_a
INSERT INTO members (email) VALUES ('Kim@Example.com')
ON CONFLICT (lower(email)) DO NOTHING;
SELECT id, email FROM members ORDER BY id;
✓ SUCCESS
INSERT 0 0
 id |      email
----+-----------------
  1 | kim@example.com
(1 row)

05A partial unique index (WHERE is_default) — "only one default address"

User 10 already has two addresses (Seoul, Busan). Adding Incheon failed with Key (user_id)=(10) already exists. That is confusing, since several rows already share user_id 10, but this index only checks rows WHERE is_default. A default address (Seoul) already existed and the insert tried to add a second one.

Setup
Setuprun as lab_a
CREATE TABLE addresses (id int PRIMARY KEY, user_id int, city text, is_default boolean NOT NULL DEFAULT false);
CREATE UNIQUE INDEX addresses_one_default ON addresses (user_id) WHERE is_default;
INSERT INTO addresses VALUES (1, 10, 'Seoul', true), (2, 10, 'Busan', false);
OUTPUT
CREATE TABLE
CREATE INDEX
INSERT 0 2
Reproducerun as lab_a
INSERT INTO addresses VALUES (3, 10, 'Incheon', true);
✕ ERROR
ERROR:  23505: duplicate key value violates unique constraint "addresses_one_default"
DETAIL:  Key (user_id)=(10) already exists.
SCHEMA NAME:  lab_a
TABLE NAME:  addresses
CONSTRAINT NAME:  addresses_one_default
Check the causerun as lab_a
SELECT indexdef FROM pg_indexes WHERE indexname = 'addresses_one_default';
SELECT id, city, is_default FROM addresses WHERE user_id = 10 ORDER BY id;
OUTPUT
                                              indexdef
-----------------------------------------------------------------------------------------------------
 CREATE UNIQUE INDEX addresses_one_default ON lab_a.addresses USING btree (user_id) WHERE is_default
(1 row)

 id | city  | is_default
----+-------+------------
  1 | Seoul | t
  2 | Busan | f
(2 rows)

indexdef ends with WHERE is_default, and user 10 already has one row with is_default = t (Seoul).

Fixrun as lab_a
BEGIN;
UPDATE addresses SET is_default = false WHERE user_id = 10 AND is_default;
INSERT INTO addresses VALUES (3, 10, 'Incheon', true);
COMMIT;
OUTPUT
BEGIN
UPDATE 1
INSERT 0 1
COMMIT

In one transaction, setting the old default to is_default = false first and then inserting the new address went through to COMMIT. Now only Incheon is t.

After the fixrun as lab_a
SELECT id, city, is_default FROM addresses WHERE user_id = 10 ORDER BY id;
✓ SUCCESS
 id |  city   | is_default
----+---------+------------
  1 | Seoul   | f
  2 | Busan   | f
  3 | Incheon | t
(3 rows)

06An UPDATE that shifts a UNIQUE column by +1 (reordering)

To push every menu item down one slot, UPDATE menu_items SET sort_order = sort_order + 1 failed with Key (sort_order)=(2) already exists. The final values 2, 3, 4 would not overlap, but a plain UNIQUE constraint is checked as each row changes. The moment 1 became 2, the old 2 had not been updated yet.

Setup
Setuprun as lab_a
CREATE TABLE menu_items (id int PRIMARY KEY, title text, sort_order int UNIQUE);
INSERT INTO menu_items VALUES (1, 'Home', 1), (2, 'Products', 2), (3, 'Contact', 3);
OUTPUT
CREATE TABLE
INSERT 0 3
Reproducerun as lab_a
UPDATE menu_items SET sort_order = sort_order + 1;
✕ ERROR
ERROR:  23505: duplicate key value violates unique constraint "menu_items_sort_order_key"
DETAIL:  Key (sort_order)=(2) already exists.
SCHEMA NAME:  lab_a
TABLE NAME:  menu_items
CONSTRAINT NAME:  menu_items_sort_order_key
Check the causerun as lab_a
SELECT conname, pg_get_constraintdef(oid) AS definition, condeferrable
FROM pg_constraint
WHERE conrelid = 'menu_items'::regclass AND contype = 'u';
OUTPUT
          conname          |     definition      | condeferrable
---------------------------+---------------------+---------------
 menu_items_sort_order_key | UNIQUE (sort_order) | f
(1 row)

The constraint UNIQUE (sort_order) has condeferrable = f: it is checked immediately for each row.

Fixrun as lab_a
ALTER TABLE menu_items DROP CONSTRAINT menu_items_sort_order_key;
ALTER TABLE menu_items ADD CONSTRAINT menu_items_sort_order_key UNIQUE (sort_order) DEFERRABLE INITIALLY IMMEDIATE;
OUTPUT
ALTER TABLE
ALTER TABLE

Recreating the constraint as DEFERRABLE INITIALLY IMMEDIATE moves the check to the end of the statement: UPDATE 3, and the order became 2, 3, 4.

After the fixrun as lab_a
UPDATE menu_items SET sort_order = sort_order + 1;
SELECT id, title, sort_order FROM menu_items ORDER BY sort_order;
✓ SUCCESS
UPDATE 3
 id |  title   | sort_order
----+----------+------------
  1 | Home     |          2
  2 | Products |          3
  3 | Contact  |          4
(3 rows)

FAQ

How do I fix duplicate key value violates unique constraint in PostgreSQL?

Read the DETAIL line to see the column and value. If the value really exists, change or skip it, or use INSERT … ON CONFLICT. If it is an auto-generated id, reset the sequence with setval to the current max(id).

Why does PostgreSQL say duplicate key on the id column when I don't insert the id?

The sequence behind the serial or identity column is behind the data, usually after importing rows with explicit ids. nextval returns a number that already exists. Fix it with SELECT setval(pg_get_serial_sequence('table', 'id'), (SELECT max(id) FROM table));.

What does SQLSTATE 23505 mean?

23505 is unique_violation: an INSERT or UPDATE would create two rows with the same value in a primary key or unique constraint.

How do I insert a row or update it if it already exists in PostgreSQL?

Use INSERT … ON CONFLICT (key_column) DO UPDATE SET col = EXCLUDED.col. EXCLUDED refers to the row you tried to insert.

Why does UPDATE ... SET sort_order = sort_order + 1 give duplicate key?

A plain UNIQUE constraint is checked row by row, so values collide mid-statement. Recreating it as DEFERRABLE INITIALLY IMMEDIATE made the same UPDATE succeed in the test.

DETAIL shows an expression like Key (lower(email)). What is that?

The unique index is on an expression, so values that differ only in case count as the same. Check indexdef in pg_indexes, then search existing rows with the same expression.

How we verify

Each scenario starts from fresh database users. A script runs the setup, confirms the exact error code, applies the fix and runs the statement again. The output shown is what the database printed, saved by the script.

lab_a and lab_b are ordinary roles created for the test, each owning a schema of the same name; postgres is the superuser. PostgreSQL 17.12