0
点赞
收藏
分享

微信扫一扫

PG唯一索引与唯一约束.sql

fbd4ffd0717b 2022-07-13 阅读 119
PG数据库


PG 唯一约束与唯一索引

  • 实例

create table test(id serial, name text);
ALTER TABLE test add CONSTtraint uk_test_name unique(name);


create table test2(id serial, name text);
create unique index idx_test2_name on test2 using btree(name);


insert into test (name) values('zhangsan'),(NULL),(NULL);
insert into test2 (name) values('zhangsan'),(NULL),(NULL);

  • 结果

test=# \d test
Table "public.test"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+----------------------------------
id | integer | | not null | nextval('test_id_seq'::regclass)
name | text | | |
Indexes:
"uk_test_name" UNIQUE CONSTRAINT, btree (name)

test=# \d test2
Table "public.test2"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+-----------------------------------
id | integer | | not null | nextval('test2_id_seq'::regclass)
name | text | | |
Indexes:
"idx_test2_name" UNIQUE, btree (name)

test=# select * from test;
id | name
----+----------
1 | zhangsan
2 |
3 |
(3 rows)

test=# select * from test2;
id | name
----+----------
1 | zhangsan
2 |
3 |
(3 rows)

test=#

限制唯一索引的多个 NULL 值

  • 实例

create table t_abc(a2 varchar(10));

CREATE UNIQUE INDEX idx_t_abc ON t_abc ((a2 is null)) WHERE a2 IS NULL;

insert into t_abc values('1');
insert into t_abc values(NULL);
insert into t_abc values(NULL);

  • 测试结果

test=# create table t_abc(a2 varchar(10));
CREATE TABLE
test=#
test=# CREATE UNIQUE INDEX idx_t_abc ON t_abc ((a2 is null)) WHERE a2 IS NULL;
CREATE INDEX
test=#
test=# insert into t_abc values('1');
INSERT 0 1
test=# insert into t_abc values(NULL);
INSERT 0 1
test=# insert into t_abc values(NULL);
ERROR: duplicate key value violates unique constraint "idx_t_abc"
DETAIL: Key ((a2 IS NULL))=(t) already exists.
test=#

  • 总结:

唯一索引与唯一约束在 PG 中功能几乎相同
唯一索引与唯一约束不能直接限制多个NULL 值
在创建唯一索引的时候可以使用额外的参数,因而可以间接实现限制 多个 NULL 值的情况


举报

相关推荐

0 条评论