How to add 'ON DELETE CASCADE' in ALTER TABLE statement

In Oracle, you can use the "ALTER TABLE ... ADD CONSTRAINT" statement to add an "ON DELETE CASCADE" constraint to a foreign key. The basic syntax of the statement is as follows:

ALTER TABLE child_table
ADD CONSTRAINT fk_name
FOREIGN KEY (child_column)
REFERENCES parent_table (parent_column)
ON DELETE CASCADE;

Where:
  • "child_table" is the table's name containing the foreign key.
  • "child_column" is the name of the foreign key column in the child table.
  • "parent_table" is the name of the table that the foreign key references.
  • "parent_column" is the name of the primary key column in the parent table.
  • "fk_name" is the name of the foreign key constraint.
An example of how you can use this statement to add an "ON DELETE CASCADE" constraint to a foreign key:

ALTER TABLE orders
ADD CONSTRAINT fk_customer_id
FOREIGN KEY (customer_id)
REFERENCES customers (customer_id)
ON DELETE CASCADE;

In this example, the foreign key constraint "fk_customer_id" is being added to the "orders" table, with the "customer_id" column in the "orders" table as the foreign key, and the "customer_id" column in the "customers" table as the primary key.

Please note that the ALTER TABLE statement will raise an error if the parent table does not have a primary key defined or if there is already a foreign key defined on the child table that references the parent table.

Additionally, you can use the ON DELETE CASCADE in conjunction with other actions like ON DELETE SET NULL or ON DELETE SET DEFAULT.