Primary Key vs Foreign Key in SQL

A primary key uniquely identifies each row in its own table; a foreign key references a primary key in another table to establish a relationship.

Published September 19, 2026

A primary key is a column (or set of columns) that uniquely identifies every row in a table and cannot contain NULL values. A foreign key is a column that references a primary key in another (or the same) table, enforcing a relationship between the two.

Common causes

  • Relational databases split data across multiple tables to avoid duplication (normalization); foreign keys are how those separate tables stay linked and consistent

How to fix it

  • Give every table a primary key — typically an auto-incrementing id column
  • Add a foreign key constraint whenever a column stores a reference to another table's primary key, so the database itself enforces that the referenced row exists
  • Decide an ON DELETE behavior for each foreign key (CASCADE, SET NULL, RESTRICT) based on whether related rows should be deleted, nulled, or blocked when the parent row is removed

Example

CREATE TABLE orders (
  id INT PRIMARY KEY AUTO_INCREMENT,
  customer_id INT,
  FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
);

FAQ

Can a foreign key be NULL?

Yes, unless the column is explicitly declared NOT NULL — a NULL foreign key simply means that particular row has no related record.

More SQL articles