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 – The first is unique value and the second is not null
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).
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.
I STUDENT relation Student_NO in Student_COURSE is a foreign key to Student_NO.
Primary key vs Foreign key-
|S.NO.||PRIMARY KEY||FOREIGN KEY|
|1||A 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.|
|2||It uniquely identifies every record in the table.||It refers to the field in a table that is the primary key of another table.|
|3||Only one primary key is allowed in a table.||More than one foreign key is allowed in a table.|
|4||It enforces two restrictions UNIQUE and Not Null constraints.||It enforces Referential integrity. It can contain duplicates.|
|5||It does not allow NULL values.||It can also contain NULL values.|
|6||Its value cannot be deleted from the parent table.||Its value can be deleted from the child table.|
So these are the main difference between them.
For other technical articles click here. Thank you