Postgresql: Changing Action For Foreign Key Constraint

时间:2017-08-13 13:40:32

标签: sql postgresql foreign-keys constraints

I have a simple table like below.

create table chemlab.rule_header (
    id           serial PRIMARY KEY,
    name         varchar(50),
    grade        varchar(20),
    class_tag    varchar(20),    --tag added to sammple if match
    parent_id    int REFERENCES chemlab.rule_header(id) DEFAULT NULL,
    unique( grade, class_tag )
)

But afterwards, I found that I need to add ON DELETE action, the default is NO ACTION. I couldn't figure out how to change the action.

Now I have to DROP & ADD

ALTER table chemlab.rule_header 
    DROP CONSTRAINT rule_header_parent_id_fkey ;
ALTER TABLE rule_header  
    ADD CONSTRAINT rule_header_parent_id_fkey 
    FOREIGN KEY (parent_id) REFERENCES chemlab.rule_header(id) ON DELETE RESTRICT;

So what is the correct syntax to alter an action on foreign key constraint ?

2 个答案:

答案 0 :(得分:5)

好吧,这不是直接改变FOREIGN KEY约束,而DROPADD仍然存在,尽管这只是一个声明:

ALTER table  chemlab.rule_header 
    DROP CONSTRAINT rule_header_parent_id_fkey,
    ADD CONSTRAINT rule_header_parent_id_fkey 
    FOREIGN KEY (parent_id) REFERENCES chemlab.rule_header(id) ON DELETE RESTRICT;

答案 1 :(得分:2)

看一下https://www.postgresql.org/docs/current/sql-altertable.html上的文档。根据我的理解,有一些选项可以更改有关约束的一些内容(例如DEFERRABLE),但不能更改操作。