Foreign Key Constraint is used, when we want to make the relationship between two tables. A column with Foreign Key in one table is used to relate Column in another table.
The main purpose of the foreign key is that table2 which has a column with a foreign key, will only able to insert data if the table2 foreign key value is already in the table1 column (column that is linked with foreign key).
It makes the database more secure. Suppose some hacker can insert invalid or not specific data, other than that we want in the database from the frontend, which may create a very big problem for us.
For example, in the case of gender - male or female, but hackers try to enter invalid data (i.e other than male and female). Therefore, it can cause a very big problem in the future.
The syntax for Foreign key-
CREATE TABLE table2
....[other column with its datatype],
FOREIGN KEY (table2_columnname ) REFERENCES table1(table1_columnname)
Example for Foreign key-
CREATE TABLE user_salary
id int primary key,
user_id int unique,
This table user_detail contains the foreign key, which is in a relationship with the user_salary table.
Without the user_salary table, the user_detail table will not be created. So first we have to create a user_salary table.
CREATE TABLE user_detail
user_id int primary key,
name varchar(50) not null,
email varchar(50) unique,
FOREIGN KEY (user_id) REFERENCES user_salary(user_id)
In this, we define user_detail - user_id with foreign key constraint in relationship with user_id of a user_salary table. With using joins we can retrieve many details from both the table simultaneously.