PostgreSQL column check constraint 检查插入数据是否为特定值

用数据库建表的时候,常有一种需求,我们希望某一行的值只能是 v1v2v3 ,在PostgreSQL中,我们可以用 check constraint 实现。

建立以下学生信息表:

create table students (
    name               varchar(40) NOT NULL,
    age                integer NOT NULL,
    sex                char(1) NOT NULL,
    country            varchar(40) NOT NULL
);

我们需要当 sex 的值为 'F' 或者 'M' ,以及 country 的值为 'China' 、 'Japan'、 'Korean' 的时候才能插入值。

create table students (
    name               varchar(40) NOT NULL,
    age                integer NOT NULL,
    sex                char(1) NOT NULL,
    country            varchar(40) NOT NULL,
    CHECK((sex = 'F' OR sex = 'M' ) AND (country = 'China' OR country = 'Japan' OR country = 'Korean'))
);

你可能感兴趣的:(PostgreSQL column check constraint 检查插入数据是否为特定值)