900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > PG唯一索引与唯一约束.sql

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

时间:2019-04-30 04:06:59

相关推荐

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

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 testTable "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 test2Table "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 | zhangsan2 | 3 | (3 rows)test=# select * from test2;id | name ----+----------1 | zhangsan2 | 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 TABLEtest=# test=# CREATE UNIQUE INDEX idx_t_abc ON t_abc ((a2 is null)) WHERE a2 IS NULL;CREATE INDEXtest=# test=# insert into t_abc values('1');INSERT 0 1test=# insert into t_abc values(NULL);INSERT 0 1test=# 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 值的情况

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。