Monday, September 10, 2012

Foreign key on delete cascade tips

Answer: The choice between on delete restrict or on delete cascade depends on the design of your application.  You have three choices for managing deletes on Oracle foreign key constraints:
alter table sample1 
   add foreign key (col1) 
references 
   sample (col2)
on delete no action;

alter table sample1 
add foreign key (col1) 
references 
   sample (col2)
on delete restrict;
alter table sample1 
add foreign key (col1) 
   references sample (col2)
on delete cascade;
When you create a foreign key constraint, Oracle default to "on delete restrict" to ensure that a parent rows cannot be deleted while a child row still exists.
However, you can also implement on delete cascade to delete all child rows when a parent row is deleted.
Using "on delete cascade" and "on delete restrict"  is used when a strict one-to-many relationship exists such that any "orphan" row violates the integrity of the data.
Also, see these important notes on foreign key indexing, especially important if you delete or update parent rows.
Many systems use "on delete cascade" when they have ad-hoc updates so that the end-user does not have to navigate the child table and delete dozens or hundreds of child entries.  Of course, using "on delete cascade" is dangerous because of possible mistakes and because issuing a single delete on a parent row might invoke thousands of deletes from the child table.
Obviously, if you are using "on delete cascade" and you do not create an index on the child parent key the deletion of a parent row would require a full-table scan of the child table, to find and delete the child rows.

http://www.dba-oracle.com/t_foreign_key_on_delete_cascade.htm

No comments:

Post a Comment