Sobes.tech
Junior — Middle

What methods and features exist for deleting data linked with foreign keys in a database?

sobes.tech AI

Answer from AI

In databases, when deleting records linked through foreign keys, it is important to consider data integrity. The main methods of deleting related information:

  1. ON DELETE CASCADE — when the parent record is deleted, all related child records linked through the foreign key are automatically deleted.
  2. ON DELETE SET NULL — when the parent record is deleted, the foreign key in the child records is set to NULL (if the field allows NULL).
  3. ON DELETE RESTRICT / NO ACTION — prevents deletion of the parent record if related child records exist.

Example of creating a table with a foreign key and cascade delete:

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE
);

Thus, when a customer is deleted from the customers table, all their orders in the orders table are automatically deleted.

It is important to choose a deletion strategy based on business logic and data integrity requirements.