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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值