In this post, I will explain What is Foreign Key?
A Foreign Key is a Column (or Set of Columns) that references a column (most often the primary key) of another table. A table containing the Foreign Key is called a child table, and a table containing Primary Key is called a parent table.
Foreign Key is used to ensure referential integrity of the data in two tables and to prevent actions that would destroy links between tables. A Foreign Key also prevents invalid data from being inserted into a Foreign Key column, because it has to be one of the values contained in a parent table referenced column.
Example of Foreign Key-
Create Foreign Key while creating a table
CREATE TABLE tbl_Student
(
StudentId INT NOT NULL,
StudentName VARCHAR(100) NULL,
CONSTRAINT pk_StudentId PRIMARY KEY (StudentId)
)
CREATE TABLE tbl_Class
(
ClassId INT NOT NULL,
ClassName VARCHAR(100) NULL,
StudentId INT NOT NULL,
CONSTRAINT pk_ClassId PRIMARY KEY (ClassId),
CONSTRAINT fk_StudentClassId FOREIGN KEY (StudentId)
REFERENCES tbl_Student(StudentId)
)
Create Foreign Key using alter table statement
ALTER TABLE tbl_Class
ADD CONSTRAINT fk_StudentClassId
FOREIGN KEY (ClassId) REFERENCES tbl_Student(StudentId);
Drop Foreign Key using alter table statement
ALTER TABLE tbl_Class
DROP CONSTRAINT fk_StudentClassId
CREATE TABLE tbl_Student
(
StudentId INT NOT NULL,
StudentName VARCHAR(100) NULL,
CONSTRAINT pk_StudentId PRIMARY KEY (StudentId)
)
CREATE TABLE tbl_Class
(
ClassId INT NOT NULL,
ClassName VARCHAR(100) NULL,
StudentId INT NOT NULL,
CONSTRAINT pk_ClassId PRIMARY KEY (ClassId),
CONSTRAINT fk_StudentClassId FOREIGN KEY (StudentId)
REFERENCES tbl_Student(StudentId)
)
Create Foreign Key using alter table statement
ALTER TABLE tbl_Class
ADD CONSTRAINT fk_StudentClassId
FOREIGN KEY (ClassId) REFERENCES tbl_Student(StudentId);
Drop Foreign Key using alter table statement
ALTER TABLE tbl_Class
DROP CONSTRAINT fk_StudentClassId