A FOREIGN KEY enforces referential integrity by ensuring that a value in one table matches a primary (or unique) key in another table. It prevents βorphanβ records and maintains relationships.
CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id)
REFERENCES customers(customer_id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
ON DELETE CASCADE removes orders if the customer is deleted; ON UPDATE CASCADE propagates changes to the key.
ALTER TABLE order_items
ADD CONSTRAINT fk_order
FOREIGN KEY (order_id)
REFERENCES orders(order_id)
ON DELETE RESTRICT
ON UPDATE CASCADE;
ALTER TABLE order_items DROP FOREIGN KEY fk_order;
fk_table_refTable).CASCADE, RESTRICT, SET NULL, or NO ACTION.INNODB storage engine to support foreign keys.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!