Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add ON DELETE constraint on the table?

Tags:

sql

mysql

How can I add ON DELETE constraint on the table?

like image 691
user505880 Avatar asked Jan 14 '11 06:01

user505880


People also ask

How do I add or delete constraints in SQL?

Constraints can be added to a new table or to an existing table. To add a unique or primary key, a referential constraint, or a check constraint, use the CREATE TABLE or the ALTER TABLE statement. To remove a constraint, use the ALTER TABLE statement.

How can constraints be added to a table?

The constraint can be created within the CREATE TABLE T-SQL command while creating the table or added using ALTER TABLE T-SQL command after creating the table. Adding the constraint after creating the table, the existing data will be checked for the constraint rule before creating that constraint.


1 Answers

Use ALTER TABLE+ADD CONSTRAINT. E.g. if you want to link tables members and profiles by member_id and cascade delete profiles each time the member is deleted, you can write something like this:

ALTER TABLE profiles    ADD CONSTRAINT `fk_test`    FOREIGN KEY (`member_id` )    REFERENCES `members` (`member_id` )    ON DELETE CASCADE 

If you will need to update that constraint - you'll have to remove it at then create again, there's no direct way to alter it.

ALTER TABLE profiles DROP FOREIGN KEY `fk_test` 
like image 186
Pavel Dubinin Avatar answered Sep 21 '22 23:09

Pavel Dubinin