PostgreSQL unique constraint allow mutiple nulls

前端之家收集整理的这篇文章主要介绍了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)

猜你在找的Postgre SQL相关文章