Sobes.tech
Middle+

What guarantees does a foreign key provide for data in a relational database? Is it possible to delete a parent record if there are foreign keys referencing it?

sobes.tech AI

Answer from AI

A foreign key in a relational database guarantees referential integrity between tables. It ensures that the value in the child (referencing) table corresponds to an existing value in the parent table.

Guarantees:

  • You cannot insert a value into the foreign key if the corresponding record in the parent table does not exist.
  • You can configure behavior on delete or update of the parent record (CASCADE, SET NULL, RESTRICT, etc.).

Can you delete a parent record if there are foreign keys referencing it?

  • If the foreign key is set with RESTRICT or NO ACTION, deleting the parent record will be prohibited as long as there are child records.
  • If CASCADE is set, deleting the parent record will automatically delete all related child records.
  • If SET NULL, deleting the parent record will set the foreign key in child records to NULL.

SQL example:

ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id) REFERENCES customers(id)
ON DELETE CASCADE;

Here, deleting a customer from the customers table will automatically delete all their orders from the orders table.

What guarantees does a foreign key provide for data… - sobes.tech