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:
CustomersTable: This table stores customer information.OrdersTable: This table stores order information and references theCustomerstable.
Table Definitions
CustomersTable
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(100),
ContactEmail VARCHAR(100)
);
OrdersTable
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
Explanation
-
CustomersTable:CustomerIDis the primary key.CustomerNameandContactEmailare additional attributes.
-
OrdersTable:OrderIDis the primary key.OrderDateis the date when the order was placed.CustomerIDis a foreign key that referencesCustomerIDin theCustomerstable.
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
Orderstable with aCustomerIDthat does not exist in theCustomerstable. - If a record in the
Customerstable is deleted, the corresponding records in theOrderstable 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.
Your Feedback
Help us improve by sharing your thoughts
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.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
