MySQL FOREIGN KEY Constraint

Introduction

The FOREIGN KEY constraint is used to create a relationship between two tables.

It ensures that values in one table must match values in another table.

This helps maintain referential integrity in databases.


Example Scenario

Consider two tables:

Customers Table

| customer_id | name |

Orders Table

| order_id | customer_id |

Here, customer_id In the Orders table, it references the Customers table.


Syntax

CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

This ensures that an order cannot exist without a valid customer.


Benefits of Foreign Key

  • Maintains relationships between tables

  • Prevents invalid data

  • Improves data consistency


Key PointsA foreign

  • A key link between two tables

  • Ensures referential integrity

  • Prevents insertion of invalid values