Is there a way to force delete all dependent rows (child rows) when you delete the parent row of a table.
I have a table with too many referential integrity. I was wondering what is the easy way to achieve this in oracle.
I appreciate your support.
You can declare foreign key constraints that cascade deletes so that child rows are automatically deleted when the parent row is deleted.
SQL> create table parent (
2 parent_key number primary key
3 );
Table created.
SQL> create table child (
2 child_key number primary key,
3 parent_key number,
4 constraint fk_child_parent foreign key( parent_key )
5 references parent( parent_key )
6 on delete cascade
7 );
Table created.
SQL> insert into parent values( 1 );
1 row created.
SQL> insert into child values( 10, 1 );
1 row created.
SQL> commit;
Commit complete.
SQL> delete from parent where parent_key = 1;
1 row deleted.
SQL> select * from child;
no rows selected
I'm personally not a fan of this sort of cascading delete-- I'd rather see the delete against the child table as part of the procedure that deletes from the parent so that the flow of the program is all in one place. Cascading foreign keys are like triggers in that they can seriously complicate the program flow by adding actions that are hard for a developer reading through code to notice and to track.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With