I'm manually constructing a DELETE CASCADE statement for postgres.
I have a 'transaction' and a 'slice' table, related as shown below:
Table "public.slice" Column | Type | Modifiers ----------+------+----------- id | text | not null name | text | Referenced by: TABLE "transaction" CONSTRAINT "transaction_slice_id_fkey" FOREIGN KEY (slice_id) REFERENCES slice(id) Table "public.transaction" Column | Type | Modifiers ----------+------+----------- id | text | not null slice_id | text | Referenced by: TABLE "classification_item" CONSTRAINT "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id) Table "public.classification_item" Column | Type | Modifiers ----------------+------+----------- id | text | not null transaction_id | text | Foreign-key constraints: "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)
Say I want to delete all transactions and classification_items referenced by the slice whose name is 'my_slice'. What do I need to write?
=# delete from classification_item where transaction_id= #...? =# delete from transaction where slice_id= #...? =# delete from slice where name='my_slice';
If the parent is not there then there should not be any child records that are referencing the deleted records of the parent. As shown above, the DELETE CASCADE can be used in PostgreSQL to delete all the child records whenever the referenced parent record is deleted automatically which helps in maintaining integrity.
ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. For example when a student registers in an online learning platform, then all the details of the student are recorded with their unique number/id.
The CASCADE option allows you to remove the table and its dependent objects. The RESTRICT option rejects the removal if there is any object depends on the table. The RESTRICT option is the default if you don't explicitly specify it in the DROP TABLE statement.
Postgres foreign keys support the CASCADE deletes:
slice_id integer REFERENCES slice(id) ON DELETE CASCADE
etc
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