Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: Changing Action For Foreign Key Constraint

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 ?

like image 951
Ben Avatar asked Aug 13 '17 13:08

Ben


People also ask

How do you update a table that has a foreign key?

Login to the SQL Server using SQL Server Management Studio, Navigate to the Keys folder in the child table. Right click on the Keys folder and select New Foreign Key. Edit table and columns specification by clicking … as shown in the below image. Select the parent table and the primary key column in the parent table.

How do I edit a PostgreSQL constraint?

You can also define a constraint on the column at the same time, using the usual syntax: ALTER TABLE products ADD COLUMN description text CHECK (description <> ''); A new column cannot have a not-null constraint since the column initially has to contain null values. But you can add a not-null constraint later.


2 Answers

Well, this not directly altering FOREIGN KEY constraint, and there are DROP and ADD still, though this is only one statement:

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;
like image 69
Oto Shavadze Avatar answered Oct 01 '22 01:10

Oto Shavadze


Take a look at the documentation at https://www.postgresql.org/docs/current/sql-altertable.html. There are options to alter a few things about a constraint (like DEFERRABLE) but not for changing the action, as I understand you need.

like image 43
acaruci Avatar answered Oct 01 '22 02:10

acaruci