FOREIGN KEY in SQL

🔗 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

The table containing the foreign key is called the child table, while the table being referenced is called the parent table.

đŸŽ¯ 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)NameDepartment
101AliceComputer Science
102BobMathematics

Child Table: Enrollments

EnrollmentIDStudentID (FK)Course
1101Database Systems
2102Data 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

The database rejects the insert because the referenced StudentID does not exist in the parent table.

➕ 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.

ActionDescription
CASCADEAutomatically updates or deletes related child rows.
SET NULLSets the foreign key value to NULL.
SET DEFAULTSets the foreign key to its default value (where supported).
RESTRICTPrevents the parent row from being modified if related child rows exist.
NO ACTIONRejects 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

The behavior and availability of referential actions vary between database systems. Review your DBMS documentation before using them.

âš–ī¸ PRIMARY KEY vs FOREIGN KEY

FeaturePRIMARY KEYFOREIGN KEY
PurposeUniquely identifies each row.Creates relationships between tables.
Duplicate Values❌ Not allowed.✅ Allowed.
NULL Values❌ Not allowed.Depends on the column definition.
Number Per TableOne 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

The data type and meaning of a foreign key column should match the referenced column to ensure valid relationships and consistent data.

âš ī¸ Best Practices

Best Practice

Define foreign keys for related tables, use meaningful constraint names, choose appropriate referential actions, ensure matching data types between related columns, and carefully plan relationships during database design to maintain referential integrity.

🚀 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.
>>"Foreign keys connect related data, transforming individual tables into a powerful relational database."

Summary

✅ The FOREIGN KEY constraint is fundamental to relational database design. It links tables together, enforces referential integrity, and ensures that relationships remain valid as data is inserted, updated, and deleted. Proper use of foreign keys leads to more consistent, reliable, and maintainable databases.