SQL FOREIGN KEY Constraint
A FOREIGN KEY
constraint in SQL is used to enforce a link between the data in two tables. It ensures that the value in a column (or a set of columns) in one table matches the value in a column (or a set of columns) in another table. This maintains the referential integrity between the tables.
Example Scenario
Let's consider a simple example involving two tables:
Customers
Table: This table stores customer information.Orders
Table: This table stores order information and references theCustomers
table.
Table Definitions
Customers
Table
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(100),
ContactEmail VARCHAR(100)
);
Orders
Table
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
Explanation
-
Customers
Table:CustomerID
is the primary key.CustomerName
andContactEmail
are additional attributes.
-
Orders
Table:OrderID
is the primary key.OrderDate
is the date when the order was placed.CustomerID
is a foreign key that referencesCustomerID
in theCustomers
table.
Example Insertions
- Inserting Data into
Customers
INSERT INTO Customers (CustomerID, CustomerName, ContactEmail)
VALUES (1, 'Alice Smith', 'alice.smith@example.com'),
(2, 'Bob Johnson', 'bob.johnson@example.com');
- Inserting Data into
Orders
INSERT INTO Orders (OrderID, OrderDate, CustomerID)
VALUES (101, '2024-07-25', 1), -- References CustomerID = 1
(102, '2024-07-26', 2); -- References CustomerID = 2
Output Verification
- Query to Retrieve Data from
Customers
SELECT * FROM Customers;
Output:
CustomerID | CustomerName | ContactEmail
-----------|--------------|----------------------
1 | Alice Smith | alice.smith@example.com
2 | Bob Johnson | bob.johnson@example.com
- Query to Retrieve Data from
Orders
SELECT * FROM Orders;
Output:
OrderID | OrderDate | CustomerID
--------|------------|-----------
101 | 2024-07-25 | 1
102 | 2024-07-26 | 2
Referential Integrity
The foreign key constraint ensures that:
- You cannot insert a record into the
Orders
table with aCustomerID
that does not exist in theCustomers
table. - If a record in the
Customers
table is deleted, the corresponding records in theOrders
table will be handled based on the configured behavior (CASCADE
,SET NULL
,NO ACTION
, etc.).
For example, if you try to insert an order with a CustomerID
that doesn't exist, the database will reject it, enforcing data consistency.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.