CodeEraFree roadmap

Blogs

Understanding Primary Keys, Foreign Keys, and Unique Constraints in SQL

Database design  , 2 min read

Primary keys, foreign keys and unique constraints keep data correct and consistent. They are rules the database enforces for you, so bad data is rejected before it gets in.

1. Primary key

A primary key is a column, or a set of columns, that uniquely identifies each row. A primary key must be unique, can never be NULL, and should not change over time. A table can have only one.

CREATE TABLE departments (
  department_id   INT PRIMARY KEY,
  department_name VARCHAR(50) NOT NULL
);

2. Foreign key

A foreign key is a column that refers to the primary key of another table. It links the two tables and enforces referential integrity: every value must exist in the referenced table, or be NULL.

CREATE TABLE employees (
  employee_id   INT PRIMARY KEY,
  name          VARCHAR(100),
  department_id INT,
  FOREIGN KEY (department_id)
    REFERENCES departments (department_id)
);

With this in place, you cannot add an employee to a department that does not exist.

3. Unique constraint

A unique constraint makes sure no two rows have the same value in a column, or the same combination of values across several columns. Use it for things like an email address that must not repeat but is not the primary key.

CREATE TABLE users (
  user_id INT PRIMARY KEY,
  email   VARCHAR(255),
  CONSTRAINT uq_users_email UNIQUE (email)
);

How they differ

Primary keyForeign keyUnique
PurposeIdentify each rowLink to another tableBlock duplicate values
Per tableOneManyMany
NULL allowedNoYesYes (SQL Server allows only one NULL)
Values must be uniqueYesNoYes

In short: primary keys identify rows, foreign keys connect tables, and unique constraints guard against duplicates. Understanding these three is the foundation of a well-designed database.