Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't create unique index in postgres, it says "key is duplicate" even when it's not

Tags:

postgresql

I created a unique index for a table and got the following error:

SQL error: ERROR: could not create unique index "unique_product" DETAIL: Key (mastercode)=() is duplicated

So i run a query to check for duplicated records and really found some duplicates:

select * from product p where (select count(*) from product pp where pp.mastercode = p.mastercode) > 1

But even after deleting them i could not create the index, it shows the same error and the query to check for duplicates shows nothing.

Looks like it didn't update the indices after deleting the duplicates, or something like that. How can i solve this?

UPDATE Something i forgot to mention but may be important, i already have an index on the field mastercode, which is a default index (not unique). Don't know if this has something to do.

like image 296
Mateus Viccari Avatar asked Aug 12 '15 12:08

Mateus Viccari


People also ask

Can unique index have duplicate values?

A unique index never has duplicate values.

Does unique index prevent duplicates?

You can prevent duplicate values in a field in an Access table by creating a unique index. A unique index is an index that requires that each value of the indexed field is unique.

Does Postgres create index on unique?

PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.

How do I change unique index in PostgreSQL?

To change the tablespace of an index, you must own the index and have CREATE privilege on the new tablespace. All indexes in the current database in a tablespace can be moved by using the ALL IN TABLESPACE form, which will lock all indexes to be moved and then move each one.


2 Answers

Check the results from this query:

SELECT  mastercode, count(*)
FROM product
GROUP BY mastercode
HAVING count(*) > 1; -- not unique
like image 137
Frank Heikens Avatar answered Sep 29 '22 15:09

Frank Heikens


I believe you have an instance of a null mastercode, and are trying to insert another null mastercode.

Try select * from product where mastercode is null;

like image 33
Tom Studee Avatar answered Sep 29 '22 14:09

Tom Studee