简体   繁体   English

使用 PostgresQL 检查现有列的约束

[英]Check constraint on existing column with PostgresQL

I'm trying to put check constraint on existing column.我正在尝试对现有列设置检查约束。

Is there any way to achieve this from PostgreSQL?有什么办法可以从 PostgreSQL 实现这一点吗?

Use alter table to add a new constraint:使用alter table添加新约束:

alter table foo 
   add constraint check_positive check (the_column > 0);

More details and examples are in the manual:更多细节和示例在手册中:
http://www.postgresql.org/docs/current/static/sql-altertable.html#AEN70043 http://www.postgresql.org/docs/current/static/sql-altertable.html#AEN70043

Edit编辑

Checking for specific values is done in the same way, by using an IN operator:通过使用IN运算符,以相同的方式检查特定值:

alter table foo 
   add constraint check_positive check (some_code in ('A','B'));

If you are okay with (or want) Postgres to generate a constraint name you can use the following shorthand syntax.如果您同意(或想要)Postgres 生成约束名称,您可以使用以下速记语法。

ALTER TABLE foo
    ADD CHECK (column_1 > 2);

You can add a new constraint with with alter table command.您可以使用alter table命令添加新约束。 From documentation this example:文档这个例子:

ALTER TABLE distributors 
ADD CONSTRAINT zipchk CHECK (char_length(zipcode) = 5) NO INHERIT;

You will have to replace constraint name as well as table name and content by your local requirements.您必须根据本地要求替换约束名称以及表名称和内容。

This should do it:这应该这样做:

create table test (
    id serial 
);

alter table test
add constraint id_not_null
check (id is not null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM