微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL unique constraint allow mutiple nulls

1. 建表

postgres=# create table tb8(id integer,name character varying);
CREATE TABLE
2. 添加唯一约束
postgres=# alter table tb8 add CONSTRAINT check_name_unique unique(name);
ALTER TABLE
postgres=# \d tb8
           Table "public.tb8"
 Column |       Type        | Modifiers 
--------+-------------------+-----------
 id     | integer           | 
 name   | character varying | 
Indexes:
    "check_name_unique" UNIQUE CONSTRAINT,btree (name)
3. 插入数据
postgres=# insert into tb8(id) select generate_series(1,5);
INSERT 0 5
postgres=# insert into tb8 select 6,'john';
INSERT 0 1.
postgres=# insert into tb8 select 7,'john';
ERROR: duplicate key value violates unique constraint "check_name_unique"
DETAIL: Key (name)=(john) already exists.

4. 查看数据:

postgres=# select * from tb8;
 id | name 
----+------
  1 | 
  2 | 
  3 | 
  4 | 
  5 | 
  6 | john
(6 rows)

唯一字段name上有多个null,null是不确定类型,即null != null,null != not null.


5. 使用distinct关键字的时候判定多个null是相等的

postgres=# select distinct name from tb8;
 name 
------
 
 john
(2 rows)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐