postgresql duplicate key violates unique constraint

Hi i have a question i know this was posted many times but i didn’t find an answer to my problem. The problem is that i have a table and a column “id” i want it to be unique number just as normal. This type of column is serial and the next value after each insert is comming from a sequence so everything seems to be all right but it still sometimes showing this error. I dont know why ? In the documentation it is writtne the sequence is fool prof and always works. If I add a UNIQUE constraint to that column will it thelp ? I worked before many times on Postres but this error is showing for me for the first time. I did everything as normal and i never had this problem before. Can you help me to find the answer that can be used in the future for all tables that will be created ? Lets say we have something easy like this:

CREATE TABLE comments
(
  id serial NOT NULL,
  some_column text NOT NULL,
  CONSTRAINT id_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE interesting.comments OWNER TO postgres;

If i add:

ALTER TABLE comments ADD CONSTRAINT id_id_key UNIQUE(id)

Will if be enought or is there some other thing that should be done ?

Leave a Comment