Cascade Delete

When the DELETE CASCADE is activated, the action of deleting a record in the primary table will automatically result in the deletion of associated records in the secondary table.

Working Sample

Consider a scenario in which there is a database containing tables named "customer_details" and "order_details". The "order_details" table is connected to the "customer_details" table by means of a foreign key restriction. In the event that a user wishes to remove a customer entry from the "customer_details" table, they may also want to eliminate all corresponding orders linked to that customer from the "order_details" table in order to maintain the organization and cleanliness of the database. This is where the DELETE CASCADE functionality in Postgres proves to be highly advantageous.

To begin with, we will establish a table named "customer_details" consisting of two columns: "cust_id" and "cust_name."

CREATE TABLE customer_details (
cust_id INTEGER PRIMARY KEY,
cust_name TEXT NOT NULL
);

Generate an additional table titled "order_details" containing two standard columns alongside a foreign key.

CREATE TABLE order_details(
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customer_details (cust_id) ON DELETE CASCADE,
order_date DATE
);

A new table called "order_details" has been constructed, which includes a foreign key named "customer_id" that has been configured to utilize the DELETE CASCADE functionality.

Let us insert records into the tables.

The "order_details" will hold this data now.

Due to the activation of the DELETE CASCADE setting during the foreign key creation process, the removal of a record from the "customer_details" table will consequently result in the deletion of the associated record from the "order_details" table as well.

DELETE FROM customer_details 
WHERE cust_id = 1;

This deleted the customer from "customer_details" table and also removed the corresponding orders from the "order_details" table.

Types

There are five possible choices available for the deletion of foreign key constraints.

Last updated