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 ?
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With