MySQL Relational Integrity Constraints
A FOREIGN KEY in MySQL creates a link between two tables. It ensures that the value in one table (child) must exist in another table (parent), which helps maintain referential integrity and prevents invalid or orphaned data.
Customers).Orders).The FOREIGN KEY constraint can be defined inside a CREATE TABLE statement. The referenced column in the parent table must be a PRIMARY KEY or have a UNIQUE constraint.
-- Define a foreign key on ID referencing another table
CREATE TABLE ChildTable (
ID INT,
FOREIGN KEY (ID) REFERENCES ParentTable(ID)
);
Here, each order must belong to a valid customer. The CustomerID column in Orders references the CustomerID column in Customers.
-- Parent table: each customer has a unique CustomerID
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(100) NOT NULL
);
-- Child table: each order must reference an existing customer
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
You can use ON DELETE and ON UPDATE to control what happens when the parent row is deleted or updated.
-- Automatically delete/update child rows when the parent changes
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID)
ON DELETE CASCADE
ON UPDATE CASCADE
);
CustomerID that does not exist in Customers, MySQL will reject the insert and throw an error.ON DELETE CASCADE is used and a customer is deleted, all their related orders in Orders will be deleted automatically.ON UPDATE CASCADE is used and a customer's CustomerID changes, the corresponding CustomerID in Orders will be updated automatically.Customers.CustomerID) is a PRIMARY KEY or has a UNIQUE constraint.ON DELETE and ON UPDATE actions:
CASCADE for automatic propagation.SET NULL if you want to keep the row but remove the reference.RESTRICT / NO ACTION to block the change when child rows exist.fk_orders_customer.Departments and Employees. Make Employees.DepartmentID a foreign key referencing Departments.DepartmentID.DepartmentID and observe the error.ON DELETE SET NULL to the foreign key and delete a department. Check the DepartmentID values in Employees.ON DELETE CASCADE and see how behavior changes when you delete a department.