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.

It enforces two restrictions on the column – First is unique value and 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 which is foreign key reference 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 an every record in the table.It refers to the field in a table which is the primary key of another table.
3Only one primary key is allowed in a table.More than one foreign keys are allowed in a table.
4It enforces two restrictions UNIQUE and Not Null constraints.It enforces Referential integrity. It can contain duplicate .
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 article click here. Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *