Difference between primary key and Foreign key
Written By:- Isha MalhotraPrimary Key V/S Foreign key
There are so many differences between primary key and foreign key and some of these are as follows: -
- a) A table can have only one primary key but we can have more than one foreign key.
- b) Primary key doesn’t accept null value but we can add null value in foreign key.
- c) Primary key doesn’t accept duplicate value but we can have duplicate value in foreign key.
- d) When we create primary key clustered index created automatically but in foreign key no index created automatically. But we can create non-clustered index manually.
- e) Primary key is used to uniquely identified the rows but foreign key refer primary in of other table.
How to Create Primary Key
create table Course(Course_Id int primary key, Course_Name varchar(100));
or
create table Course(Course_Id int Constraint CPk primary key(Course_Id), Course_Name varchar(100));
or
create table Course(Course_Id int Constraint CPk primary key, Course_Name varchar(100));
or
create table Course(Course_Id int , Course_Name varchar(100) Constraint CPk primary key(Course_Id));
In this table you can see that in enq_type column we have entered null as we don’t have any value for this row.
How to Create Foreign Key
create table t3(id int primary key, phone varchar (100), email varchar (200));
create table t4(id int foreign key references t3(id), fees int);