Saturday, 25 January 2020

How to create a Foreign Key in SQL Server

Hi All,

Hope you all are doing good.

In this article, we will know about how to create Foreign Key relation between two tables.
Please go through below query.

CREATE TABLE [Departments] (
[DepartmentId] INT IDENTITY PRIMARY KEY,
[DepartmentName] NVARCHAR(50)  NULL
);

CREATE TABLE [Students] (
[StudentId] INT IDENTITY PRIMARY KEY,
[StudentName] NVARCHAR(50)  NULL,
[DepartmentId] INTEGER  NOT NULL,
[DateOfBirth] DATE  NULL,
CONSTRAINT FK_Students_Departments FOREIGN KEY (DepartmentId) REFERENCES Departments (DepartmentId)
);

Below picture depicts that each department can contain any number of students.

The output of the above relation will be like as in below picture.

To add a Foreign Key for a table which was created earlier, use below statement.

Let us assume that you have created a Students table with any Foreign Key and now if you want to add a Foreign Key relation to that table use below command.

ALTER TABLE Students
ADD CONSTRAINT FK_Students_Departments 
FOREIGN KEY (DepartmentId) 
REFERENCES Departments(DepartmentId)

Thanks for reading my article.

No comments:

Post a Comment

Intoduction to Flutter

Hi All, I hope every one is doing good In this article, we will know about the introduction of Flutter.