4

Can I execute something like this in Postgresql, that is, execute CASCADE DELETE for just one statement?

DELETE CASCADE FROM foo WHERE bar = 'baz';

My goal is to delete not just the selected record(s) from table foo, but all the records in all the tables where foo.id column is used as a foreign key, without adding the constraint for the entire table foo: ON DELETE CASCADE.

Related:

Timur Shtatland
  • 125
  • 2
  • 11

2 Answers2

6

There is no way to automatically delete all dependent rows; you will have to delete them before you delete the referenced row.

Laurenz Albe
  • 61,070
  • 4
  • 55
  • 90
1
  1. ALTER and UPDATE each child table to have a copy of the field bar from its parent record in foo.
  2. DELETE all rows in each child table where bar = 'baz'.
  3. Clean up by ALTER DROP COLUMN on the new fields which are no longer needed.
  4. Finally, DELETE the parent table's rows where bar = 'baz'.
Bruce
  • 111
  • 2