Foreign Keys

In relational database design, a foreign key is a column or a set of columns in one table that uniquely identifies a row of another table. The table containing the foreign key is called the child table, and the table containing the primary key is called the parent table.

Foreign keys are crucial for establishing and enforcing relationships between tables. They ensure data integrity by maintaining referential integrity, which means that if a value is present in a foreign key column, it must also exist in the referenced primary key column of the parent table.

Why Use Foreign Keys?

Defining a Foreign Key

When defining a foreign key, you specify:

Example Scenario

Consider two tables: Customers and Orders.

Customers Table (Parent Table)

CustomerID (PK) FirstName LastName Email
101 Alice Smith alice.s@example.com
102 Bob Johnson bob.j@example.com

CustomerID is the Primary Key.

Orders Table (Child Table)

OrderID (PK) OrderDate CustomerID (FK) TotalAmount
5001 2023-10-26 101 150.75
5002 2023-10-27 102 75.50
5003 2023-10-27 101 220.00

CustomerID in the Orders table is a Foreign Key referencing Customers.OrderID.

SQL Syntax Example

Here's how you might define the Orders table with a foreign key constraint in SQL:

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    OrderDate DATE NOT NULL,
    CustomerID INT,
    TotalAmount DECIMAL(10, 2) NOT NULL,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
        ON DELETE SET NULL
        ON UPDATE CASCADE
);

In this example:

Note: The behavior of ON DELETE and ON UPDATE actions can vary slightly between different database systems (e.g., SQL Server, PostgreSQL, MySQL).

Referential Integrity Actions

When a change occurs in the parent table that affects a referenced primary key, the database can take specific actions on the child table based on the foreign key constraint:

Common Pitfalls

Understanding and correctly implementing foreign keys is fundamental to building robust and reliable relational databases. They are the backbone of data integrity and structure.