A foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table. The table containing the foreign key is known as the child table, and the table containing the candidate key is known as the parent table. The purpose of the foreign key is to ensure referential integrity of the data. In SQL Server, foreign keys are used to enforce relationships between tables.
Key Concepts
Referential Integrity: Ensures that relationships between tables remain consistent. When one table has a foreign key to another table, it ensures that the values in the foreign key column must exist in the primary key column of the referenced table.
Parent Table: The table containing the primary key that the foreign key references.
Child Table: The table containing the foreign key that references the parent table.
Cascade Actions: SQL Server supports different actions like CASCADE, SET NULL, and SET DEFAULT for DELETE and UPDATE operations to maintain referential integrity.
Creating Foreign Keys
To create a foreign key in SQL Server, you can use the FOREIGN KEY constraint within the CREATE TABLE or ALTER TABLE statements.
Syntax for CREATE TABLE:
CREATE TABLE ChildTable ( ChildID int NOT NULL, ParentID int, PRIMARY KEY (ChildID), FOREIGN KEY (ParentID) REFERENCES ParentTable(ParentID) );
Syntax for ALTER TABLE:
ALTER TABLE ChildTable ADD CONSTRAINT FK_ChildTable_ParentID FOREIGN KEY (ParentID) REFERENCES ParentTable(ParentID);
Example
Consider two tables: Orders (the child table) and Customers (the parent table).
CREATE TABLE Customers ( CustomerID int PRIMARY KEY, CustomerName varchar(255) NOT NULL ); CREATE TABLE Orders ( OrderID int PRIMARY KEY, OrderDate datetime NOT NULL, CustomerID int, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) );
In this example, CustomerID in the Orders table is a foreign key referencing the CustomerID in the Customers table. This ensures that any value entered in the CustomerID column of the Orders table must exist in the CustomerID column of the Customers table.
Cascade Actions
SQL Server allows you to specify actions to take when a referenced row is updated or deleted. These actions include:
CASCADE: Automatically updates or deletes the rows in the child table when the corresponding row in the parent table is updated or deleted.
SET NULL: Sets the foreign key column to NULL when the corresponding row in the parent table is deleted.
SET DEFAULT: Sets the foreign key column to its default value when the corresponding row in the parent table is deleted.
NO ACTION: Prevents the delete or update operation on the parent table if there is a related row in the child table.
Example with Cascade Actions:
CREATE TABLE Orders ( OrderID int PRIMARY KEY, OrderDate datetime NOT NULL, CustomerID int, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ON DELETE CASCADE ON UPDATE CASCADE );
In this example, if a row in the Customers table is deleted, all corresponding rows in the Orders table will also be deleted. Similarly, if the CustomerID in the Customers table is updated, the CustomerID in the Orders table will also be updated to maintain referential integrity.
Managing Foreign Keys
Adding a Foreign Key: Use the ALTER TABLE statement to add a foreign key constraint to an existing table.
Dropping a Foreign Key: Use the ALTER TABLE statement to drop a foreign key constraint.
Dropping a Foreign Key example:
ALTER TABLE Orders DROP CONSTRAINT FK_Orders_Customers;
In this command, FK_Orders_Customers is the name of the foreign key constraint.
Conclusion
Foreign keys are essential for maintaining the integrity and consistency of data across related tables in SQL Server. By enforcing referential integrity, they help ensure that relationships between tables remain valid, thus preventing orphaned records and maintaining data accuracy. Understanding how to create, manage, and use foreign keys effectively is crucial for database design and maintenance.