Difference between Primary key and foreign key in sql server

Primary key
Foreign key
Primary key is a unique value identity of a particular row in a table.
Foreign key is a reference key between two tables when the column or columns that hold the primary key value for one table.
Example:-

CREATE TABLE TBL_Info
(
P_Id int NOT NULL PRIMARY KEY,
Name varchar(255) NOT NULL,
Gender varchar(7),
City varchar(255)
)

Example:-

CREATE TABLE TBL_Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES TBL_Info(P_Id)
)
Primary Key does not contain the null value
Foreign key can have multiple null values.
A table contain only one primary key.
A table contain multiple foreign keys that can reference with different tables.
Primary Key can be duplicate. That’s means primary key column can not be save same value.
Foreign key can be duplicated. That’s means foreign key column can be save same value

We can define primary key constraint on temporary table
We can’t define foreign key constraint on temporary table
We can define primary key constraint on table variable
We can't define foreign key constraint on table variable
By default, Primary key is clustered index
Foreign key do not automatically create an index, clustered or non-clustered. You can manually create an index on foreign key.
We can insert a value in primary key column that may or may not be present in child table that containing the foreign key.
We can not insert a value in foreign key column that is not present in the primary key column in the referenced parent table. 
We can't delete primary key value from the parent table which is used as a foreign key in child table. To delete we first need to delete that primary key value from the child table.
We can delete the foreign key value from the child table even though that refers to the primary key of the parent table.

Difference between Primary key and foreign key in sql server Difference between Primary key and foreign key in sql server Reviewed by NEERAJ SRIVASTAVA on 8:22:00 PM Rating: 5

No comments:

Powered by Blogger.