Sqlite NULL 且唯一?

标签 sql sqlite null unique unique-constraint

<分区>

我注意到我可以在具有 UNIQUE 约束的列中使用 NULL 值:UNIQUE(col)

在某些情况下这会产生任何问题吗?

最佳答案

虽然以下内容解决了多个空值,但它解决与此类设计相关的任何“问题”,除了可能的数据库/SQL 可移植性 - 因此,它可能 被认为是一个答案,并留在这里仅供引用。


这实际上包含在 SQLite FAQ 中。这是一种设计选择 - SQLite(与 SQL Server 不同)选择多个 NULL 值计入索引中的唯一性。

The SQL standard requires that a UNIQUE constraint be enforced even if one or more of the columns in the constraint are NULL, but SQLite does not do this. Isn't that a bug?

Perhaps you are referring to the following statement from SQL92:

  • A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns.

That statement is ambiguous, having at least two possible interpretations:

  1. A unique constraint is satisfied if and only if no two rows in a table have the same values and have non-null values in the unique columns.

  2. A unique constraint is satisfied if and only if no two rows in a table have the same values in the subset of unique columns that are not null.

SQLite follows interpretation (1), as does PostgreSQL, MySQL, Oracle, and Firebird. It is true that Informix and Microsoft SQL Server use interpretation (2), however we the SQLite developers hold that interpretation (1) is the most natural reading of the requirement and we also want to maximize compatibility with other SQL database engines, and most other database engines also go with (1), so that is what SQLite does.

查看 comparison of NULL handling .

关于Sqlite NULL 且唯一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22699409/

相关文章:

JavaOptional.ifPresentOrElse 带返回值

python - MySQL 和 Python : How to map the table data?

sql - 如何在 postgresql 中以不同方式更新共享相同 id 的每一行?

sql - PostgreSQL Varchar UID 到 Int UID,同时保持唯一性

php - 为 MySQL 编写的 PDO 脚本是否应该与 Oracle 一起使用?

python-3.x - 在 Python3 中使用 SQLAlchemy 在 sqlite3 数据库中存储和读取文件

ruby-on-rails - rails yaml fixture - 指定 NULL 值

c++ - 套接字缓冲区中烦人的 NUL block

SQL 帮助 - SELECT/WHERE/CASE?

android - 哪个java ORM适用于android OS并支持惰性列表?