SQL Server › Constraints (Primary Key, Foreign Key, Check & Unique)

What is a foreign key constraint, and how does it help maintain data integrity between two related tables?

Beginner

Answer

A foreign key constraint links a column in one table to the primary key of another table, ensuring that any value entered in that column must already exist in the referenced table, which prevents situations like an order being created for a customer id that does not actually exist.
CREATE TABLE Orders (
  OrderId INT PRIMARY KEY,
  CustomerId INT,
  FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
);
Real-world example An order management system uses a foreign key to guarantee every order is linked to a valid, existing customer, preventing orphaned orders that reference customers who were never actually added to the system.

Common follow-ups: What happens if you try to delete a customer who still has related orders?;Can a foreign key reference a column in the same table it is defined on?