What are Primary Keys and Foreign Keys?

A primary key is a field or group of fields that uniquely identify a record in a table. Primary key fields cannot be NULL and cannot contain duplicate values.

If you want to link two tables, then primary key of one table will be added to another table where primary key of first table will be become the foreign key of second table.

Consider the following two tables.

Department Table

Department_ID (Primary Key) Department_Name
01 Computers
02 Physics
03 Electronics

Employee Table

Employee_ID (Primary Key) Name Place
001 Jim New York
002 Jack London
003 Robin Sydney
004 Raj Bangalore

If you want to link department table and employee table, then add the primary key of department table i.e. Department_ID to employee table. Department_ID becomes the foreign key of employee table and Department table becomes the check table.

Employee table after creating foreign key.

Employee_ID (Primary Key) Name Place Department_ID (Foreign Key)
001 Jim New York 01
002 Jack London 01
003 Robin Sydney 02
004 Raj Bangalore 03

The main purpose of the foreign key is data validation. This will not allow entering a Department_ID in the employee table that is not there in the department table. For example if you try to create a record in employee table with Department_ID as ’04’, it will throw an error.


4 Comments

  1. thanks very much. YOu answered very simple way but stupid recruiter need only theritical because he already studied theritical notes right

Leave a Reply

Your email address will not be published.


*