Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres ERROR:duplicate key value violates unique constraint

Tags:

postgresql

Table defintion is

create table users (
serial_no integer PRIMARY KEY DEFAULT nextval('serial'),
uid bigint NOT NULL,
username varchar(32),
name text,
CONSTRAINT production UNIQUE(uid)
);

I used this query

INSERT INTO users (uid) values(123) ;

It says duplicate key value violates unique constraint. So I googled it and found this link

So I tried

INSERT INTO users (uid) values(123) 
where 1 in (select 1 from users where uid = 123) ;

It says yntax error at or near "WHERE".

How to use a statement of insert into using the where clause so that when I run the same query using php it does not return an error

column uid is unique

like image 926
Anubhav Agarwal Avatar asked Feb 11 '12 19:02

Anubhav Agarwal


People also ask

How to fix duplicate key value violates unique constraint?

How to fix PostgreSQL error "duplicate key violates unique constraint" SELECT setval('the_primary_key_sequence', (SELECT MAX(the_primary_key) FROM the_table)+1); That will set the sequence to the next available value that's higher than any existing primary key in the sequence.

What does duplicate key value mean?

A duplicate key error means that you have tried to insert a row with the same key value as some other row already indexed by the named index.

What does the unique constraint do in PostgreSQL?

PostgreSQL provides you with the UNIQUE constraint that maintains the uniqueness of the data correctly. When a UNIQUE constraint is in place, every time you insert a new row, it checks if the value is already in the table. It rejects the change and issues an error if the value already exists.


1 Answers

The INSERT statement doesn't support a WHERE clause. Run this.

create table test (
  n integer primary key
);

insert into test values (1);
insert into test values (2) where true;

That will give you a syntax error because of the WHERE clause.

SELECT statements can have a WHERE clause, though. This will insert 2 into the test table one time. Run it as many times as you want; it won't raise an error. (But it will insert only one row at the most.)

insert into test (n) 
select 2 where 2 not in (select n from test where n = 2);

So your query, assuming you're trying to avoid raising an error on a duplicate key, should be something like this.

INSERT INTO users (uid) 
SELECT 123 WHERE 123 not in (SELECT uid FROM users WHERE uid = 123) ;
like image 65
Mike Sherrill 'Cat Recall' Avatar answered Oct 04 '22 13:10

Mike Sherrill 'Cat Recall'