What is Foreign Key in SQL Server?
In SQL Server, a foreign key is a column or a set of columns in a table that establishes a relationship between two tables. It ensures referential integrity by enforcing that the values in the foreign key column(s) exist in the referenced table's primary key column(s).
Here are some key points to understand about foreign keys in SQL Server:
- Relationship Establishment: A foreign key establishes a relationship between two tables, typically referred to as the referencing table (child table) and the referenced table (parent table). The foreign key column(s) in the referencing table references the primary key column(s) in the referenced table.
- Referential Integrity: The foreign key constraint ensures referential integrity by enforcing that the values in the foreign key column(s) exist in the primary key column(s) of the referenced table. This means that any value in the foreign key column(s) must match an existing value in the referenced table's primary key column(s).
- Cascading Actions: SQL Server allows you to specify cascading actions to be performed when a referenced row is updated or deleted. Cascading actions include cascading updates and cascading deletes, which automatically propagate changes to the referencing table when a change is made to the referenced table.
- Multiple Foreign Keys: A table can have multiple foreign keys, each representing a different relationship with other tables. Each foreign key references a specific primary key column(s) in the referenced table.
Example:
Let's consider two tables, "Orders" and "Customers," where the "Orders" table has a foreign key relationship with the "Customers" table.
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100)
);
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
In this example, the "Customers" table has a primary key column "CustomerID," which uniquely identifies each customer. The "Orders" table has a foreign key column "CustomerID" that references the "CustomerID" column in the "Customers" table.
The foreign key constraint FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ensures that any value in the "CustomerID" column of the "Orders" table must exist in the "CustomerID" column of the "Customers" table. This maintains the referential integrity between the two tables, allowing for consistent and reliable relationships between customers and their orders.