What is a foreign key ?

Let's take an example to understand about the foreign key


You are creating a database for an EBay like application. So you need minimum two tables, one to store the product categories and the other one to store the products. It is important to add a primary key to any table you create. Below are the two tables and the columns


Table : ProductCategories


Columns :

  1. Id ( PK )
  2. Name

Table : Products

Columns :

  1. Id ( PK )
  2. Name
  3. Price

 

Now if you think a little bit you will realize that the products table above is missing one important column. Which one ? It's the Category column. You definitely want to categories the products you add to the products table and for this you need to category column. So our products table will look like this

  1. Id ( PK )
  2. Name
  3. Price
  4. CategoryId

Now suppose you have 3 categories for which your application will be selling products

 

Id Name
1 Laptop
2 Cloths
3 Shoes

 

Now that we have defined the categories, lets add products to the products column

 

Id Name Price CategoryId
1 Dell 35000 1
2 Levis Jeans 1000 2
3 Reebok 2500 3
4 Acer 30000 1
5 Samsung 15000 4
6 Addidas 3000 3

 

Now look at the data in the table above. Look at the category id for record number 5. It's category id is 4. But when you look at your categories table you see that there is no record with id 4. So this record then in the products table is garbage, means it has no meaning.

Definition of a foreign key


A foreign key is a column in a table that maps with the primary key column of another table. Whenever you add a new record to the table with the foreign key your table will refer to the other table to ask if the value of the foreign key you have entered is correct. If yes it will save the data, if no it will not save the data.


Difference between a primary and a foreign key

  1. Primary key helps you keep all the records in your table unique
  2. Foreign key helps to link two tables. It will make sure that all the data you are entering for foreign key is correct by asking the connected table.

Related Questions

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp