Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL UNIQUE index not unique?

Tags:

postgresql

I have a table with a 12-column UNIQUE index. \d sales shows sales_uq UNIQUE, btree (a1, a2, a3, ... a12).

I do the following query:

SELECT a1, a2, a3, ... a12 FROM sales GROUP BY a1, a2, a3, ... a12 HAVING count(1) > 1;

and I get a bunch of results. How is that possible?! Is it possible that the index is there but somehow disabled? Or can there be some issue with NULLs? Or with floating point numbers (two of the columns in the index are of type double precision)?

like image 466
ibz Avatar asked Aug 17 '10 06:08

ibz


2 Answers

because two NULLs don't compare as equal, they play funny games with UNIQUE constraints.

See last paragraph of UNIQUE constraints in the PostgreSQL documentation:

In general, a unique constraint is violated when there are two or more rows in the table where the values of all of the columns included in the constraint are equal. However, two null values are not considered equal in this comparison. That means even in the presence of a unique constraint it is possible to store duplicate rows that contain a null value in at least one of the constrained columns.

like image 100
Damien_The_Unbeliever Avatar answered Sep 29 '22 08:09

Damien_The_Unbeliever


A double is inexact, that's why this might happen. Use an exact datatype and you won't have problems like this.

like image 20
Frank Heikens Avatar answered Sep 29 '22 09:09

Frank Heikens