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
CREATE TABLE members (id int PRIMARY KEY, email text UNIQUE, name text);
INSERT INTO members VALUES (1, 'kim@example.com', 'Kim');CREATE TABLE
INSERT 0 1INSERT INTO members VALUES (2, 'kim@example.com', 'Kim2');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_keySELECT id, email, name FROM members WHERE email = 'kim@example.com'; id | email | name
----+-----------------+------
1 | kim@example.com | Kim
(1 row)INSERT INTO members VALUES (2, 'lee@example.com', 'Lee');
SELECT id, email FROM members ORDER BY id;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
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;CREATE TABLE
INSERT 0 10INSERT INTO orders (item) VALUES ('new');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_pkeySELECT max(id) AS max_id, (SELECT last_value FROM orders_id_seq) AS seq_last FROM orders; max_id | seq_last
--------+----------
10 | 4
(1 row)SELECT setval(pg_get_serial_sequence('orders', 'id'), (SELECT max(id) FROM orders)); 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.
INSERT INTO orders (item) VALUES ('new') RETURNING id; id
----
11
(1 row)
INSERT 0 103The 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
CREATE TABLE stock (sku text PRIMARY KEY, qty int NOT NULL);
INSERT INTO stock VALUES ('A-100', 5);CREATE TABLE
INSERT 0 1INSERT INTO stock VALUES ('A-100', 7);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_pkeySELECT * FROM stock WHERE sku = 'A-100'; sku | qty
-------+-----
A-100 | 5
(1 row)INSERT INTO stock VALUES ('A-100', 7)
ON CONFLICT (sku) DO UPDATE SET qty = EXCLUDED.qty;
SELECT * FROM stock;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
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');CREATE TABLE
CREATE INDEX
INSERT 0 1INSERT INTO members (email) VALUES ('Kim@Example.com');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_uqSELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'members' ORDER BY indexname;
SELECT id, email FROM members WHERE lower(email) = lower('Kim@Example.com'); 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.
SELECT id, email FROM members WHERE lower(email) = lower('Kim@Example.com'); 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.
INSERT INTO members (email) VALUES ('Kim@Example.com')
ON CONFLICT (lower(email)) DO NOTHING;
SELECT id, email FROM members ORDER BY id;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
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);CREATE TABLE
CREATE INDEX
INSERT 0 2INSERT INTO addresses VALUES (3, 10, 'Incheon', true);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_defaultSELECT indexdef FROM pg_indexes WHERE indexname = 'addresses_one_default';
SELECT id, city, is_default FROM addresses WHERE user_id = 10 ORDER BY id; 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).
BEGIN;
UPDATE addresses SET is_default = false WHERE user_id = 10 AND is_default;
INSERT INTO addresses VALUES (3, 10, 'Incheon', true);
COMMIT;BEGIN
UPDATE 1
INSERT 0 1
COMMITIn 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.
SELECT id, city, is_default FROM addresses WHERE user_id = 10 ORDER BY id; 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
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);CREATE TABLE
INSERT 0 3UPDATE menu_items SET sort_order = sort_order + 1;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_keySELECT conname, pg_get_constraintdef(oid) AS definition, condeferrable
FROM pg_constraint
WHERE conrelid = 'menu_items'::regclass AND contype = 'u'; 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.
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;ALTER TABLE
ALTER TABLERecreating the constraint as DEFERRABLE INITIALLY IMMEDIATE moves the check to the end of the statement: UPDATE 3, and the order became 2, 3, 4.
UPDATE menu_items SET sort_order = sort_order + 1;
SELECT id, title, sort_order FROM menu_items ORDER BY sort_order;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