CASCADE
CASCADE is an option in SQL that automatically propagates changes from a parent entity to a child entity in a relational database management system. In the context of foreign key constraints, CASCADE ensures that action performed on the parent table (such as DELETE or UPDATE) are also performed on the associated records in the child table to maintain data consistency and referential integrity.
Example
Output
The DELETE statement does not provide a visible output when executed. It does its job in the background.
Explanation
In the given code, we created a table orders
with a foreign key customer_id
that references the customer_id
in the customers
table. The ON DELETE CASCADE
clause specifies that when a customer record in the customers
table is deleted, then all corresponding records in the orders
table for that customer should also be deleted automatically. In the last command, we deleted a customer with customer_id = 1
from the customers
table, which also deleted all orders related to this customer from the orders
table thanks to the CASCADE
option.
Example
If the related product row is deleted from the products
table, the corresponding rows in the orders
table will be deleted due to the CASCADE
rule.
Output
This output indicates that the orders
table has been successfully created with an implied sequence for the order_no
column.
Explanation
In the code example, a new table ‘orders’ is created with two columns: ‘order_no’ and ‘product_no’. The ‘product_no’ column references the ‘products’ table. The ON DELETE CASCADE
rule is applied, meaning if a referenced row in the ‘products’ table is deleted, all rows in ‘orders’ table that hold a reference to it will also be deleted. The output confirms the successful creation of the ‘orders’ table with an automatic sequence created for the ‘order_no’ column.
Example
Output
Command(s) completed successfully.
CREATE TABLE Parent ( id INT, PRIMARY KEY(id) );
CREATE TABLE Child ( id INT, parent_id INT, FOREIGN KEY(parent_id) REFERENCES Parent(id) ON DELETE CASCADE );
INSERT INTO Parent (id) VALUES (1); INSERT INTO Child (id, parent_id) VALUES (1, 1); DELETE FROM Parent WHERE id=1;
No rows in set (0.01 sec)
Output
Explanation
This provided SQL script first enables the foreign_keys
feature in SQLite, because it’s turned off by default. It then goes on to declare two tables: artist
and track
. The track
table has a foreign key trackartist
that references artistid
in the artist
table. Through the ON DELETE CASCADE
rule, any deletion of a record in the artist
table triggers the deletion of all associated records in the track
table. After inserting example data into both tables, deleting the artist with artistid=1
also deletes the track with trackid=1
due to the cascade effect. The output queries for both the tables return nothing proving the cascade delete.