on delete cascade in sql ? can you explain with example?
Thanks in Advance.
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Chintan RathodPosted Dec 5, 2012, 8:48 AM
What is a foreign key?
A foreign key means that values in one table must also appear in another table.
The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table.
A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table with automatically be deleted. This is called a cascade delete.
A foreign key with a cascade delete can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
Using a CREATE TABLE statement
The syntax for creating a foreign key using a CREATE TABLE statement is:
For Example
In this example, we've created a primary key on the supplier table called supplier_pk. It consists of only one field - the supplier_id field. Then we've created a foreign key called fk_supplier on the products table that references the supplier table based on the supplier_id field.
Because of the cascade delete, when a record in the supplier table is deleted, all records in the products table will also be deleted that have the same supplier_id value.
We could also create a foreign key (with a cascade delete) with more than one field as in the example below:
In this example, our foreign key called fk_foreign_comp references the supplier table based on two fields - the supplier_id and supplier_name fields.
The cascade delete on the foreign key called fk_foreign_comp causes all corresponding records in the products table to be cascade deleted when a record in the supplier table is deleted, based on supplier_id and supplier_name.
Using an ALTER TABLE statement
The syntax for creating a foreign key in an ALTER TABLE statement is:
For Example
In this example, we've created a foreign key (with a cascade delete) called fk_supplier that references the supplier table based on the supplier_id field.
We could also create a foreign key (with a cascade delete) with more than one field as in the example below:
Reference:http://www.techonthenet.com/oracle/foreign_keys/foreign_delete.php
Thanks