Difference Between Primary key and Foreign key in DBMS

DBMSData StorageData Structure

In this post, we will understand the difference between Primary key and Foreign key in DBMS

Primary key

  • It is used to ensure that the data in the specific column is unique.

  • It helps uniquely identify a record in a relational database.

  • One primary key only is allowed in a table.

  • It is a combination of the ‘UNIQUE’ and ‘Not Null’ constraints.

  • This means it can’t be a NULL value.

  • Its value can’t be deleted from parent table.

  • The constraint can be implicitly defined for the temporary tables.

Example- In SQL:

CREATE TABLE table_name (
col_name int NOT NULL PRIMARY KEY,
….
);

Foreign Key

  • It is a column or a group of columns in a relational database table.

  • It gives a link between the data in both the tables.

  • It is the field in a table which is analogous to primary key of other table.

  • More than one foreign key is allowed in a table.

  • It can contain duplicate values in a relational database.

  • It can contain NULL values.

  • Its value can be deleted from the child table.

  • The constraint can’t be defined on local or global temporary tables.

Example- in SQL:

CREATE TABLE table_name (
   col_name int NOT NULL PRIMARY KEY,
   col_name int FOREIGN KEY REFERENCES Persons(col_name)
);
raja
Published on 25-Mar-2021 10:36:59
Advertisements