SQL FOREIGN KEY Constraint

A FOREIGN KEY constraint in a database ensures referential integrity between two tables. It means a value in one table must exist in another table.

A foreign key is a column (or set of columns) in one table that references the primary key in another table.
It prevents invalid data relationships.

Customers Table (Parent Table)

CREATE TABLE Customers (
    customer_id INT PRIMARY KEY,
    customer_name VARCHAR(50)
);

Orders Table (Child Table)

CREATE TABLE Orders (
    order_id INT PRIMARY KEY,
    order_date DATE,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);

Here:
   • Customers.customer_id → Primary Key
   • Orders.customer_id → Foreign Key
This ensures every order belongs to a valid customer.

Short definition:
A foreign key is a column in one table that references the primary key of another table to maintain referential integrity.


Topics