Online Training for MVC Web Designing Development, MS SQL, Digital Marketing

SQL Database Foreign key constraint Example


A FOREIGN KEY in SQL is a key used to link two SQL tables together.

The table holding the foreign key reference is called the child table

Let’s look at the picture below
Here table "tbClassTeacherMap" is having a foreign key column called "TeacherId" , and the Foreign key Constraint name Is "FK_ tbClassTeacherMap_tbTeacher"

How to create foreign key in SQL

So far you have understood what is Foreign key column, and what is Foreign Key Constraint, Now you learn how to create Foreign Key Constraint.

You can create Foreign Key two ways
  • At the time of Table Creation
    CREATE TABLE ClassStudentMap (
    CSId int not null identity(1,1) PRIMARY KEY,
    ClassId int NOT NULL,
    StudentId bigint NOT NULL,
    CONSTRAINT FK_ClassStudentMap_Student FOREIGN KEY (StudentId)
    REFERENCES tbStudent(StudentId)

  • Or you can Alter the Table
    alter TABLE ClassStudentMap

    add CONSTRAINT FK_ClassStudentMap_ClassRoom FOREIGN KEY (ClassId)
    REFERENCES tbClassRoom(crId)

FOREIGN KEY Constraint in SQL Server

FOREIGN KEY Reference in SQL
Group Training