How to Create FOREIGN KEY Constraints in SQL

In this article I am going to explain about FOREIGN KEY Constraints in SQL.
  • 2338

Introduction

A foreign key in a table is a column or combination of columns that is used to establish  a relationship between two tables in database. FOREIGN KEY constraint is used to create a foreign key in a table at the time of table creation.

Foreign key establish a link between two tables. Foreign key in one table is primary key of second table.

Example of Primary key Constraint and foreign key constraint

empid in empinfo table is primary key and depid in depinfo table is primary key. depid works as foreign key in empinfo table.

create table empinfo

(

empid int primary key,

depid int foreign key references depinfo(depid) ,

name varchar(15),

age int,

city varchar(15),

salary money

)


 

create table depinfo

(

depid int primary key ,

depname varchar(15),

dephead varchar(15)

)


© 2020 DotNetHeaven. All rights reserved.