Foreign
key in SQL Server
A foreign key is a way to enforce referential integrity within
your SQL Server database.
A foreign key means that values in one table must also appear in
another table.
The referenced table is called the parent table while
the table with the foreign key is called the child table
The foreign key in the child table will generally reference a primary key in the parent table.
A foreign
key can be created using either a CREATE TABLE statement or an ALTER TABLE
statement.
The foreign
key constraint prevents invalid data form being inserted into the foreign key
column.
Example 1
CREATE TABLE products
( product_id INT constraint product_pk PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
category VARCHAR(25)
);
CREATE TABLE inventory
(
inventory_id INT constraint inventory_pk PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product_id FOREIGN KEY (product_id) REFERENCES products (product_id)
);
Example 2
CREATE TABLE products
(
product_name VARCHAR(50) NOT NULL,
location VARCHAR(50) NOT NULL,
category VARCHAR(25)
CONSTRAINT products_pk PRIMARY KEY (product_name, location)
);
CREATE TABLE inventory
(
inventory_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
location VARCHAR(50) NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product FOREIGN KEY (product_name, location)
REFERENCES products (product_name, location)
);
Foreign
key - Using ALTER TABLE statement
Example 1
ALTER TABLE inventory
ADD CONSTRAINT fk_inv_product_id
FOREIGN KEY (product_id)
REFERENCES products (product_id);
Example 2
ALTER TABLE inventory
ADD CONSTRAINT fk_inv_product
FOREIGN KEY (product_name, location)
REFERENCES products (product_name, location);