SQL Foreign Key

A Foreign Key is a column (or set of columns) in one table that references the Primary Key of another table.
It is used to create a relationship between two tables and maintain data integrity.

Why Foreign Keys Are Used
Foreign keys ensure that:
   • Data between tables stays consistent
   • You cannot insert invalid data
   • Relationships between tables are maintained
Example:
If an order belongs to a customer, the order must reference an existing customer.

Creating a Foreign Key in SQL

CREATE TABLE Customers (
    CustomerID INT PRIMARY KEY,
    Name VARCHAR(50)
);

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT,
    Amount INT,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

Explanation:
CustomerID in Orders references CustomerID in Customers.
You cannot insert a CustomerID that does not exist in Customers table.

Simple Definition
👉 A Foreign Key is a column that connects one table to another table using the Primary Key.
It helps create relationships between tables.


Topics