Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one write a DELETE CASCADE for postgres?

Tags:

sql

postgresql

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'; 
like image 203
AP257 Avatar asked Sep 14 '10 17:09

AP257


People also ask

How does cascade work in PostgreSQL?

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.

What is on delete cascade example?

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.

What is drop cascade in PostgreSQL?

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.


1 Answers

Postgres foreign keys support the CASCADE deletes:

slice_id integer REFERENCES slice(id) ON DELETE CASCADE 

etc

like image 181
jira Avatar answered Oct 14 '22 10:10

jira