pg 18的not null 约束
在pg 17中,我们在创建约束的时候不支持约束暂时不生效,但是18中提供了此功能:
下面是相关测试:
首先 pg17中:
zc=# select version();
version
PostgreSQL 17.4 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit
(1 row)
zc=# drop table t;
DROP TABLE
zc=# create table t ( a int not null, b text );
CREATE TABLE
zc=# \d t
Table “public.t”
Column | Type | Collation | Nullable | Default
--------±--------±----------±---------±--------
a | integer | | not null |
b | text | | |
zc=# insert into t select null,1 from generate_series(1,2);
ERROR: null value in column “a” of relation “t” violates not-null constraint
DETAIL: Failing row contains (null, 1).
通过上面的测试可以看到我们默认情况下pg会检查 not null约束,影响了我们的数据插入。
pg 18中的测试情况:
我们可以先不加not null 约束,等插入数据后添加 not null 约束但是 not valid
修改数据都正常后再使他valid
postgres=# select version();
version
PostgreSQL 18devel on x86_64-pc-linux-gnu, compiled by gcc (GCC) 8.3.1 20191121 (Red Hat 8.3.1-5), 64-bit
(1 row)
postgres=# drop table t;
DROP TABLE
postgres=# create table t ( a int, b text );
CREATE TABLE
postgres=# insert into t select null,1 from generate_series(1,2);
INSERT 0 2
postgres=# alter table t add constraint c1 not null a not valid;
ALTER TABLE
postgres=# select * from t;
a | b
—±–
| 1
| 1
(2 rows)
postgres=# update t set a = 1;
UPDATE 2
postgres=# alter table t validate constraint c1;
ALTER TABLE
postgres=# insert into t values (null, ‘a’);
ERROR: null value in column “a” of relation “t” violates not-null constraint
DETAIL: Failing row contains (null, a).
pg 17测试相关语法:
zc=# select version();
version
PostgreSQL 17.4 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit
(1 row)
zc=# drop table t;
DROP TABLE
zc=# create table t ( a int, b text );
CREATE TABLE
zc=# insert into t select null,1 from generate_series(1,2);
INSERT 0 2
zc=# alter table t add constraint c1 not null a not valid;
ERROR: syntax error at or near “not”
LINE 1: alter table t add constraint c1 not null a not valid;
可以看到pg17中相关语法是暂时不支持的。




