How do you create a foreign key constraint with ON DELETE CASCADE?
Posted by TinaGrn
Last Updated: July 13, 2024
Creating a foreign key constraint with ON DELETE CASCADE ensures that when a record in the parent table is deleted, all corresponding records in the child table are automatically deleted. This can be useful for maintaining referential integrity in your database. Here is how to create a foreign key constraint with ON DELETE CASCADE in SQL for a typical relational database management system (RDBMS) like MySQL, PostgreSQL, SQL Server, or Oracle.
Example Scenario:
Let's say you have two tables: orders (child table) and customers (parent table). The orders table has a foreign key customer_id that references the id column in the customers table.
SQL Syntax
Creating Tables with Foreign Key Constraint
1. Creating the Parent Table (customers):
CREATE TABLE customers (
       id INT PRIMARY KEY,
       name VARCHAR(100)
   );
2. Creating the Child Table (orders) with ON DELETE CASCADE:
CREATE TABLE orders (
       order_id INT PRIMARY KEY,
       customer_id INT,
       order_date DATE,
       FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
   );
Adding a Foreign Key Constraint to an Existing Table
If your orders table already exists and you want to add the foreign key constraint with ON DELETE CASCADE, you can do it with an ALTER TABLE statement:
ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id)
REFERENCES customers(id)
ON DELETE CASCADE;
Important Considerations
- Make sure that the data types of the foreign key column (customer_id in orders) and the referenced column (id in customers) are compatible. - When you delete a record in the parent table (customers), all dependent records in the child table (orders) will be automatically deleted. - Care should be taken when using ON DELETE CASCADE, as it may lead to unintentional loss of data if not managed carefully.
Example Usage
Now, when you perform a delete operation on a customer, it will also delete all orders associated with that customer:
DELETE FROM customers WHERE id = 1;
If there are any orders in the orders table that reference customer_id = 1, those orders will be deleted automatically due to the cascade effect of the foreign key constraint.