I have a table with a 12-column UNI开发者_如何学GoQUE 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
)?
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.
A double is inexact, that's why this might happen. Use an exact datatype and you won't have problems like this.
精彩评论