# Foreign Key in SQL

## 🟢 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)

```sql
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)

```sql
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):

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

### ✅ Then insert orders (Child table):

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

### ❌ Invalid Example (This will fail):

```sql
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

| Term | Meaning |
| --- | --- |
| Primary Key | Unique identifier in a table |
| Foreign Key | Reference to a primary key in another table |
| Parent Table | Table with the primary key |
| Child Table | Table with the foreign key |

---
