0

Given the table definition:

CREATE TABLE devices
(
  id            SERIAL PRIMARY KEY,
  device_id     TEXT   NOT NULL,
  device_name   TEXT   NOT NULL
);

CREATE UNIQUE INDEX devices_by_device_id_unique ON devices (device_id);

And this upsert:

INSERT INTO devices (device_id, device_name)
VALUES (:device_id, :device_name)
ON CONFLICT (device_id) DO UPDATE
SET device_name = :device_name

How is it possible to get the following error:

org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "devices_pkey"
  Detail: Key (id)=(253) already exists.

Since the id column is auto-generated, it shouldn't be possible to attempt to insert the same value twice?

1 Answer 1

4

If you specify the ID value, the sequence won't be updated automatically:

insert into devices (id, device_id,device_name) values (1,1,'one');
INSERT 0 1
insert into devices (device_id,device_name) values (2,'two');
ERROR:  duplicate key value violates unique constraint "devices_pkey"
DETAIL:  Key (id)=(1) already exists.

You can reset the sequence to the current max value

SELECT setval(
          pg_get_serial_sequence('public.devices','id'), 
          max(id)) 
FROM public.devices;   
Sign up to request clarification or add additional context in comments.

3 Comments

> "If you specify the ID value" But the ID is never specified.
But maybe someone did a manual insert, for testing purposes 🤔
Concluded that thats what probably happened, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.