Oracle Foreign Key

What is Foreign Key?

1) A foreign key in SQL is a key that is used to link two tables together. 
2) The tables are liked on the basis of Column name and datatype of the Columns.
3) Primary key for a table acts as a foreign key for another table.
4) To understand the concept better kindly refer to the diagram below:

what is primary key and foreign key in oracle

Now the above-pasted diagram shows two tables i.e. Stu Table and Marks Table.

In the Stu table, we have the Roll_No attribute as a Primary key and we can notice that Roll_No is a common column in both the table with the same name, size, and datatype. That means both tables can be linked using the same column. Thus, the Roll_No column that acts as a Primary key for the Stu table, will act as a Foreign key for Marks table.

Foreign Key Syntax in Oracle

Create table Table_name
(
Col1 datatype(size),
Col2 datatype(size),....
FOREIGN KEY (Primary_key attribute) 
REFERENCES 
Reference_Table( Foreign_Key attribute)
);

Foreign Key Example in Oracle

You made a Table named Stuuu wherein you have Roll_no as a primary key. follow the code to do that same:

create table stuuu(
Name varchar(20),
Section Varchar(10),
Roll_no Number (20) ,
Subject_ID Number(20),
Subject Varchar(20),
PRIMARY KEY(Roll_no));

Now, you want to create a table named Marks having the same column Roll_no that will act as a foreign key of the table with reference to Stuuu Table. Follow the code for the same:

Create table marks
(
Roll_no Number(20),
Marks number(20),
Foreign Key(Roll_no)REFERENCES Stuuu(Roll_no)
);

Output

foreign key in oracle example