Difference between Primary Key and Foreign Key

Difference between Primary Key and Foreign Key

So the difference between Primary Key and Foreign Key is the most asked question of the interview. This is a very important concept.

Before discussing the differences first we have to understand what is the primary key and foreign key.

What is Primary Key:


A primary key is a one-column or combination of the column with a unique value for each row or tuple.

The value of the primary key must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.

Difference between Primary Key and Foreign Key
Difference between Primary Key and Foreign Key

It enforces two restrictions on the column – The first is unique value and the second is not null

Example: 
Student_NO, as well as Student_Phone both, are candidate keys for relation STUDENT but Student_NO can be chosen as the primary key (only one out of many candidate keys).

difference-between-primary-key-and-foreign-key

What is Foreign Key:


A foreign key is an attribute or group of attributes in a table that provides a link or relation between data in two tables.

In a foreign table column is a foreign key reference to a column of another table.

Example: 
I STUDENT relation Student_NO in Student_COURSE is a foreign key to Student_NO.

Primary key vs Foreign key-

S.NO.PRIMARY KEYFOREIGN KEY
1A primary key is used to ensure data in the specific column is unique and not null.A foreign key is a column or group of columns in a relational database table that provides a link between data in other tables.
2It uniquely identifies every record in the table.It refers to the field in a table that is the primary key of another table.
3Only one primary key is allowed in a table.More than one foreign key is allowed in a table.
4It enforces two restrictions UNIQUE and Not Null constraints.It enforces Referential integrity. It can contain duplicates.
5It does not allow NULL values.It can also contain NULL values.
6Its value cannot be deleted from the parent table.Its value can be deleted from the child table.
difference-between-primary-key-and-foreign-key

So these are the main difference between them.

For other technical articles click here. Thank you

Leave a Comment