Explain the mechanism of ON DELETE SET NULL in the context of relationships between database tables.
sobes.tech AI
Answer from AI
ON DELETE SET NULL is a referential action rule in a database that applies when a related record in the parent table is deleted.
If a foreign key exists in the child table referencing the parent table, and a record in the parent table that is referenced by the foreign key is deleted, instead of deleting the child record or rejecting the operation, the foreign key value in the child table is set to NULL.
This allows the child records to be preserved, but indicates that the relationship with the parent record is now absent.
Example:
Table orders with a foreign key customer_id referencing the customers table:
ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id) REFERENCES customers(id)
ON DELETE SET NULL;
If a customer is deleted from customers, then NULL will be recorded in orders.customer_id for related orders.
This is useful when deleting a parent should not lead to the deletion of child records, but the relationship should be broken.