Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle - Deleting child rows

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.

like image 573
kalls Avatar asked Jan 19 '23 23:01

kalls


1 Answers

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.

like image 62
Justin Cave Avatar answered Jan 28 '23 01:01

Justin Cave