Skip to main content

Command Palette

Search for a command to run...

Foreign Key in SQL

Updated
2 min readView as Markdown

🟢 What is a Foreign Key in SQL?

A foreign key is a column (or a group of columns) in one table that links to the primary key in another table.

  • It is used to maintain relationships between tables.

  • It ensures data consistency by restricting invalid data from being entered.

  • It creates a parent-child relationship between the tables.


🧩 Example to Understand Foreign Key

Imagine we have two tables:

  1. Customers – stores customer information

  2. Orders – stores order information made by customers

Each order must be linked to a customer.


🔹 Table 1: Customers (Parent Table)

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

Here:

  • CustomerID is the Primary Key (Unique for each customer)

🔹 Table 2: Orders (Child Table with Foreign Key)

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

Here:

  • CustomerID is a Foreign Key

  • It refers to CustomerID in the Customers table

  • This means each order must belong to a valid customer


📥 Inserting Data into Tables

✅ First insert customers (Parent table):

INSERT INTO Customers (CustomerID, Name, City)
VALUES 
(1, 'Amit Kumar', 'Delhi'),
(2, 'Ravi Singh', 'Mumbai'),
(3, 'Neha Sharma', 'Bangalore');

✅ Then insert orders (Child table):

INSERT INTO Orders (OrderID, OrderDate, CustomerID)
VALUES 
(101, '2025-08-01', 1),
(102, '2025-08-02', 2);

❌ Invalid Example (This will fail):

INSERT INTO Orders (OrderID, OrderDate, CustomerID)
VALUES (103, '2025-08-03', 5);  -- CustomerID 5 does not exist in Customers

❗ This will give an error because CustomerID = 5 is not present in the Customers table.
This is how foreign keys prevent invalid relationships.


📌 Summary

TermMeaning
Primary KeyUnique identifier in a table
Foreign KeyReference to a primary key in another table
Parent TableTable with the primary key
Child TableTable with the foreign key

More from this blog

Amit singh's blog

235 posts