What is Primary Key and Foreign Key? With Example? DBMS Part-4

What is Primary Key and Foreign Key? With Example? DBMS Part-4

Primary Key and Foreign Key

Primary Key:

It is a unique value that is used to identify a row in a table.

If you are thinking about unique constant, then you must to know the difference unique contant can store null values also primary key can not store null values.

Syntax:-

create table tablename(

column1 datatype,

column2 datatype,

……………………………..

primary key (column name)

);

A table can contain only one Primary Key.

Foreign Key:

It is a key which is used to link two table together.

Foreign Key can have multiple null value.

Syntex:-

create table tablename(

column1 datatype,

column2 datatype,

…………………………….

foreign key [column1, column2,……………….]

references [primary key table name]

);

Let’s take Example:- (Student Table)

Roll No.NameAddress
1Lav pratapDelhi
2HarshitMumbai
3Aayan KrishnaKolkata

Primary Key

-Name and Address are not unique.

-Here Roll No. is unique.

-So we discussed before, primary key is unique and not null value.

Result Table

MathsScienceEnglish
10%80%70%
90%60%80%
70%50%60%

-You want to check Roll NO. 3 Marks in Maths, Foreign Key come into picture Student Table + Result Table.

We have to add Primary Key in Result Table which act as Foreign Key.

Foreign Key

MathsScienceEnglishRoll No.
10%80%70%1
90%60%80%2
70%50%60%3

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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