đ The FOREIGN KEY constraint in SQL is used to create and enforce relationships between tables. It ensures that values in one table correspond to valid values in another table, maintaining referential integrity throughout the database.
đ What is a FOREIGN KEY?
A FOREIGN KEY is a column (or a group of columns) in one table that references the PRIMARY KEY or a UNIQUE column in another table. This relationship prevents invalid references and ensures that related data remains consistent.
Information
đ¯ Why Use FOREIGN KEY?
Foreign keys are essential for maintaining relationships between related tables in relational databases.
- đ Maintain referential integrity.
- đ Prevent invalid references.
- đ Connect related tables.
- đ Reduce duplicate data.
- đ Support efficient relational database design.
đ Parent and Child Tables
Consider the following two tables.
Parent Table: Students
| StudentID (PK) | Name | Department |
|---|---|---|
| 101 | Alice | Computer Science |
| 102 | Bob | Mathematics |
Child Table: Enrollments
| EnrollmentID | StudentID (FK) | Course |
|---|---|---|
| 1 | 101 | Database Systems |
| 2 | 102 | Data Structures |
đ Basic Syntax
FOREIGN KEY Syntax
CREATE TABLE child_table
(
column_name data_type,
FOREIGN KEY (column_name)
REFERENCES parent_table(parent_column)
);đĄ Create a Table with a FOREIGN KEY
Create an Enrollments table that references the Students table.
FOREIGN KEY Example
CREATE TABLE Enrollments
(
EnrollmentID INT PRIMARY KEY,
StudentID INT,
CourseName VARCHAR(100),
FOREIGN KEY (StudentID)
REFERENCES Students(StudentID)
);Here, every StudentID stored in the Enrollments table must already exist in the Students table.
â Valid INSERT
Since student 101 exists in the parent table, the insert succeeds.
Valid FOREIGN KEY Value
INSERT INTO Enrollments
VALUES
(1, 101, 'Database Systems');â Invalid INSERT
The following statement fails because student 999 does not exist.
Invalid FOREIGN KEY Value
INSERT INTO Enrollments
VALUES
(2, 999, 'Operating Systems');Error
â Add a FOREIGN KEY to an Existing Table
A foreign key can also be added after the table has been created.
Add FOREIGN KEY
ALTER TABLE Enrollments
ADD CONSTRAINT FK_Enrollments_Students
FOREIGN KEY (StudentID)
REFERENCES Students(StudentID);â Remove a FOREIGN KEY
Foreign key constraints can be removed when they are no longer required.
Drop FOREIGN KEY (MySQL Example)
ALTER TABLE Enrollments
DROP FOREIGN KEY FK_Enrollments_Students;Drop FOREIGN KEY (SQL Server Example)
ALTER TABLE Enrollments
DROP CONSTRAINT FK_Enrollments_Students;đ Referential Actions
Foreign keys can define what happens when rows in the parent table are updated or deleted.
| Action | Description |
|---|---|
| CASCADE | Automatically updates or deletes related child rows. |
| SET NULL | Sets the foreign key value to NULL. |
| SET DEFAULT | Sets the foreign key to its default value (where supported). |
| RESTRICT | Prevents the parent row from being modified if related child rows exist. |
| NO ACTION | Rejects the operation if referential integrity would be violated. |
FOREIGN KEY with CASCADE
CREATE TABLE Enrollments
(
EnrollmentID INT PRIMARY KEY,
StudentID INT,
FOREIGN KEY (StudentID)
REFERENCES Students(StudentID)
ON DELETE CASCADE
ON UPDATE CASCADE
);Important
âī¸ PRIMARY KEY vs FOREIGN KEY
| Feature | PRIMARY KEY | FOREIGN KEY |
|---|---|---|
| Purpose | Uniquely identifies each row. | Creates relationships between tables. |
| Duplicate Values | â Not allowed. | â Allowed. |
| NULL Values | â Not allowed. | Depends on the column definition. |
| Number Per Table | One primary key. | Multiple foreign keys. |
đŧ Real-World Example
In an e-commerce application, every order belongs to a customer. The Orders table stores a CustomerID foreign key that references the Customers table, ensuring orders are always linked to valid customers.
Orders Table
CREATE TABLE Orders
(
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID)
);â ī¸ Common Mistakes
- â Referencing a column that is not a PRIMARY KEY or UNIQUE key.
- â Inserting child records before the parent record exists.
- â Deleting parent rows without considering related child rows.
- â Using incompatible data types between the foreign key and referenced column.
Warning
â ī¸ Best Practices
Best Practice
đ Key Points to Remember
- đ A FOREIGN KEY creates relationships between tables.
- đ It references a PRIMARY KEY or UNIQUE column in another table.
- đ It helps enforce referential integrity.
- đ Child records cannot reference non-existent parent records.
- đ Referential actions such as CASCADE and SET NULL control update and delete behavior.
- đ A well-designed foreign key structure improves database consistency and reliability.