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. | Name | Address |
1 | Lav pratap | Delhi |
2 | Harshit | Mumbai |
3 | Aayan Krishna | Kolkata |
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
Maths | Science | English |
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
Maths | Science | English | Roll No. |
10% | 80% | 70% | 1 |
90% | 60% | 80% | 2 |
70% | 50% | 60% | 3 |