Wednesday, June 5, 2013

How to add ON DELETE CASCADE feature to a table/constraint when the foreign key constraint is already added?

Well, I figured out that we cannot add ON DELETE CASCADE to an existing constraint or already added foreign key constraint. You need to drop the constraint and recreate it with the ON DELETE CASCADE added to it. Here is how you can do it.

1.First drop the constraint.
2.Add the new constraint with ON DELETE CASCADE option.

Here is the example of syntax:

ALTER TABLE table_1
DROP CONSTRAINT constraint_1

This will drop the constraint.

ALTER TABLE table_1
DROP CONSTRAINT constraint_1 FOREIGN KEY(a) REFERENCES table_2(a)
ON DELETE CASCADE

This option will enable you to delete the child record automatically whenever the parent record is deleted.

No comments:

Post a Comment