Possible to specify unique index with NULLs allowed in Rails/ActiveRecord?

后端 未结 2 1752
失恋的感觉
失恋的感觉 2021-02-06 22:15

I want to specify a unique index on a column, but I also need to allow NULL values (multiple records can have NULL values). When testing with PostgreSQ

2条回答
  •  礼貌的吻别
    2021-02-06 22:57

    To clarify why this works at the database level, you have to understand the three-valued logic used in SQL: true, false, null.

    null is typically taken to mean unknown, therefore its semantics in operations are usually equivalent to not knowing what that particular value is and seeing if you can still work out an answer. So for instance 1.0 * null is null but null OR true is true. In the first case, multiplication by an unknown is unknown, but in the second, the second half of the conditional makes the whole statement always true so it doesn't matter what is on the left side.

    Now when it comes to indexes, the standard does not specify anything so vendors are left to interpret what unknown means. Personally, I think a unique index should be defined as in the PostgreSQL docs:

    When an index is declared unique, multiple table rows with equal indexed values will not be allowed

    The question should then be what is the value of null = null? The correct answer should be null. So if you read a bit between the lines of those PostgreSQL docs and say that a unique index will disallow multiple rows for which the equality operator returns true for said value then multiple null values should be allowed. This is exactly how PostgreSQL works, so in that setup you can have a unique column with multiple rows having null as a value.

    On the other hand, if you wanted to interpret the definition of a unique index to be disallow multiple rows for which the inequality operator does not return false, then you would not be able to have multiple rows with null values. Who would choose to operate in this contrapositive setup? This is how Microsoft SQL Server chooses to define a unique index.

    Both of these ways of defining a unique index are correct based on the 2003 SQL standard's definition of null. So it really depends on your underlying database. But that being said, I think the majority operate similar to PostgreSQL.

提交回复
热议问题