A FOREIGN KEY
is a column (or a set of columns) in one table that uniquely identifies a row of another table. It creates a relationship between two tables, ensuring referential integrity. The foreign key in the child table references the primary key in the parent table.
The basic syntax for defining a foreign key is as follows:
CREATE TABLE child_table (
column1 datatype,
column2 datatype,
FOREIGN KEY (foreign_key_column) REFERENCES parent_table(primary_key_column)
);
Here’s an example of creating two tables with a foreign key relationship:
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(100)
);
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
This ensures that each order is associated with a valid customer.
Foreign keys can also enforce cascading actions, which automatically update or delete related records. For example:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
ON DELETE CASCADE ON UPDATE CASCADE
);
This means if a customer is deleted, all their orders will also be deleted.
When using the FOREIGN KEY
constraint, keep in mind: