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).




