SQL Foreign Keys

A Foreign Key is a column or a set of columns in one table that uniquely identifies a row of another table. The foreign key constraint is used to link two tables together.

It ensures referential integrity, meaning that a value in the foreign key column(s) must exist in the referenced primary key column(s) of the parent table, or be NULL (if allowed).

Purpose of Foreign Keys

Syntax for Creating Foreign Keys

When Creating a Table:

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT,
    OrderDate DATE,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

Adding to an Existing Table:

ALTER TABLE Orders
ADD CONSTRAINT FK_CustomerOrder
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);

Key Concepts

Referenced Table (Parent Table)

This is the table that the foreign key points to. It typically contains the primary key that the foreign key column references.

Referencing Table (Child Table)

This is the table that contains the foreign key column(s).

Foreign Key Constraints Actions

When defining a foreign key, you can specify actions to take when data in the parent table is modified. These actions ensure consistency across related tables.

ON DELETE Actions:

ON UPDATE Actions:

Example with Actions:

CREATE TABLE Products (
    ProductID INT PRIMARY KEY,
    ProductName VARCHAR(255)
);

CREATE TABLE OrderDetails (
    OrderDetailID INT PRIMARY KEY,
    OrderID INT,
    ProductID INT,
    Quantity INT,
    FOREIGN KEY (ProductID) REFERENCES Products(ProductID)
        ON DELETE SET NULL
        ON UPDATE CASCADE
);

Important Note

The column(s) referenced by a foreign key constraint must be a primary key or a unique key in the parent table.

Best Practices