SQL Server Interview Question #16
What is a foreign key?
SQL Server Fundamentals Junior Beginner
Detailed Explanation
A foreign key establishes and enforces a relationship between tables. Values in the child table must correspond to valid referenced key values in the parent table, subject to the constraint definition.
Foreign keys help enforce referential integrity and prevent invalid relationships, such as assigning a product to a category that does not exist.
Code Example
CREATE TABLE Categories
(
Id INT PRIMARY KEY,
Name NVARCHAR(100) NOT NULL
);
CREATE TABLE Products
(
Id INT PRIMARY KEY,
Name NVARCHAR(200) NOT NULL,
CategoryId INT NOT NULL,
CONSTRAINT FK_Products_Categories
FOREIGN KEY (CategoryId)
REFERENCES Categories(Id)
);