PostgreSQL 15 提交了一个不错的功能:添加 UNIQUE null 处理选项。它是关于什么的?如果我们做一个小例子来展示这个新功能的效果,答案就很简单了。
考虑下表和唯一索引:
postgres=# create table t ( a int );
CREATE TABLE
postgres=# create unique index i on t ( a );
CREATE INDEX
这显然会阻止我们多次添加相同的值:
postgres=# insert into t values (1);
INSERT 0 1
postgres=# insert into t values (1);
ERROR: duplicate key value violates unique constraint "i"
DETAIL: Key (a)=(1) already exists.
但是 NULL 呢?NULL 表示未定义,那么当你尝试插入多个值为 NULL 的行时,唯一索引应该怎么做呢?两个 NULL 值是否相同?如果你问 PostgreSQL NULL 是否等于 NULL,你会得到 undefined(或 NULL):
postgres=# select null = null;
?column?
----------
(1 row)
将未定义的事物与未定义的事物进行比较没有多大意义。我们在上面创建的唯一索引的行为完全像这样:
postgres=# insert into t values(null);
INSERT 0 1
postgres=# insert into t values(null);
INSERT 0 1
postgres=# insert into t values(null);
INSERT 0 1
postgres=# insert into t values(null);
INSERT 0 1
postgres=# insert into t values(null);
INSERT 0 1
PostgreSQL 15 将在这里为您提供选择:
postgres=# create table tt ( a int );
CREATE TABLE
postgres=# create unique index ii on tt (a) nulls not distinct;
CREATE INDEX
postgres=# insert into tt values(null);
INSERT 0 1
postgres=# insert into tt values(null);
ERROR: duplicate key value violates unique constraint "ii"
DETAIL: Key (a)=(null) already exists.
当然,默认值是我们现在拥有的行为,但也可以显式请求:
postgres=# create unique index iii on tt (a) nulls distinct;
CREATE INDEX
OK.
文章来源:Daniel Westermann
https://blog.dbi-services.com/postgresql-15-new-option-for-null-handling-in-unique-constraints/
最后修改时间:2022-05-24 17:01:40
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




