暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Check约束,插入数值为NULL测试

原创 许玉冲 2023-03-21
383

Check约束

Check约束用以限制单列的可能取值范围,需要在Check约束中指定逻辑表达式,该逻辑表达式必须返回逻辑值(TRUE或FALSE),在Check中,把UNKNOWN值认为是TRUE。


测试环境pg:

关系型数据库的逻辑运算的结果是三值型的,TRUE,FALSE和UNKNOWN,特别是,NULL值和任何值都不相等,任何值和NULL的比较,返回的逻辑结果都是unknown。

当null和数值比较,返回结果为UNKNOWN。

postgres=# select null>0;
?column?
----------

(1 row)


#当插入数值为NULL,插入成功。

postgres=# create table pg(sn integer primary key,id integer,check(sn>0 and id<0));
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pg_pkey" for table "pg"
CREATE TABLE
postgres=# insert into pg values(3,NULL);
INSERT 0 1
postgres=# SELECT * FROM PG;
sn | id
----+----
3 |
(1 row)

postgres=# create table pg1(sn integer primary key,id integer,check(sn>0 and id>0));
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pg1_pkey" for table "pg1"
CREATE TABLE
postgres=# insert into pg1 values(3,NULL);
INSERT 0 1
postgres=# SELECT * FROM PG1;
sn | id
----+----
3 |
(1 row)

postgres=# create table pg2(sn integer primary key,id integer,check(sn>0 and id=0));
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "pg2_pkey" for table "pg2"
CREATE TABLE
postgres=# insert into pg2 values(3,NULL);
INSERT 0 1
postgres=# SELECT * FROM PG2;
sn | id
----+----
3 |
(1 row)

postgres=# 

postgres=# insert into pg2 values(NULL,NULL);
ERROR: null value in column "sn" violates not-null constraint
DETAIL: Failing row contains (null, null).



「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论