In SQL, a FOREIGN KEY constraint is a way to enforce referential integrity between two tables. It ensures that the values in a column (or columns) in one table match the values in a column (or columns) in another table's PRIMARY KEY or UNIQUE constraint.
Here's a basic example:
Suppose you have two tables: Orders
and Customers
. Each order is associated with a customer. You can enforce this relationship using a FOREIGN KEY constraint
CREATE TABLE Customers ( CustomerID INT PRIMARY KEY, CustomerName VARCHAR(255) ); CREATE TABLE Orders ( OrderID INT PRIMARY KEY, OrderDate DATE, CustomerID INT, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) );
In this example:
Customers
table has a primary key CustomerID
.Orders
table has a foreign key CustomerID
, which references the CustomerID
column in the Customers
table.CustomerID
in the Orders
table must exist in the CustomerID
column of the Customers
table. It maintains referential integrity between the two tables.When using FOREIGN KEY constraints, it's important to note the following:
Foreign key constraints are a fundamental part of maintaining data integrity in relational databases, ensuring that relationships between tables remain consistent and valid.