SQL Constraint - Foreign Key

FOREIGN KEY Constraint

The Foreign Key Constraints is used to link two tables together.

The foreign key from one table is linked to the primary key from another table.

SQL FOREIGN KEY ON CREATE TABLE

Syntax

CREATE TABLE <TABLE_NAME>(
    <COLUMN_NAME> <DATATYPE>,
    <COLUMN_NAME> <DATATYPE>,
    <COLUMN_NAME> <DATATYPE> FOREIGN KEY REFERENCES <MASTER_TABLE>(<COLUMN_NAME>)
);

Example

CREATE TABLE Employee(
    Emp_id Integer PRIMARY KEY,
    Emp_Name Varchar(20),
    Emp_Gender Varchar(10),
    Dept_Id Integer FOREIGN KEY REFERENCES Department(Dept_Id)
);

SQL FOREIGN KEY ON ALTER TABLE

Syntax

ALTER TABLE <TABLE_NAME>
ADD FOREIGN KEY (<COLUMN_NAME>) REFERENCES <MASTER_TABLE> (<COLUMN_NAME>);

Example

ALTER TABLE Employee
ADD FOREIGN KEY (Dept_Id) REFERENCES Department(Dept_Id);

Summary

The Foreign Key Constraints is used to link two tables together.

Next Recommended Reading Foreign Key with Delete CASCADE in SQL