DEV Community

Cover image for Primary Key vs Foreign Key vs Unique vs Index: A SQL Cheat Sheet
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

Primary Key vs Foreign Key vs Unique vs Index: A SQL Cheat Sheet

When you design a table, four words keep coming up: primary key, foreign key, unique and index. They are often declared on the same columns and they sometimes create the same structures behind the scenes, so it is easy to mix them up. They answer four different questions:

  • Primary key: how do I identify one row?
  • Foreign key: which row in another table does this row point to?
  • Unique: which values must never appear twice?
  • Index: how do I find rows fast?

The first three are constraints: rules the database enforces on your data. The fourth is a performance structure: it changes speed, not what data is allowed (except for a unique index, which is both).

A small example

CREATE TABLE users (
  id     BIGINT PRIMARY KEY,
  email  TEXT NOT NULL UNIQUE,
  name   TEXT
);

CREATE TABLE orders (
  id         BIGINT PRIMARY KEY,
  user_id    BIGINT NOT NULL REFERENCES users(id),
  created_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX orders_user_id_idx ON orders (user_id);
Enter fullscreen mode Exit fullscreen mode
  • users.id and orders.id are primary keys: each row has exactly one, never null, never repeated.
  • users.email is unique: two users cannot share an email.
  • orders.user_id is a foreign key: every order must point to an existing user.
  • orders_user_id_idx is a plain index: it makes "all orders of user 42" fast.

Side by side

Primary key Foreign key Unique Index
Purpose Identify each row Link to a row in another table Forbid duplicate values Speed up lookups and sorts
Per table One (can span several columns) Many Many Many
NULL allowed No Yes, unless NOT NULL Yes (rules vary by database) Yes
Duplicates No Yes No Yes (unless unique index)
Creates an index Yes, automatically Not in PostgreSQL; MySQL InnoDB does Yes, automatically It is the index
Enforces a rule Yes Yes, referential integrity Yes No

Primary key

A primary key is the identity of a row. It combines UNIQUE and NOT NULL, and a table has at most one. It can be a single column (id) or several (PRIMARY KEY (order_id, product_id) in a join table).

The common choice is a surrogate key: an auto-increment integer or a UUID that has no business meaning. Natural keys, like an email or a national ID, look tempting but tend to change, and changing a primary key means updating every row that references it.

Every major database builds an index for the primary key automatically. In MySQL with InnoDB, the table itself is stored ordered by the primary key (a clustered index), so a short, ever-increasing key keeps inserts cheap.

Foreign key

A foreign key says "this value must exist in that other table's key". The database rejects an order with user_id = 999 if user 999 does not exist, and it decides what happens when the referenced row is deleted:

  • ON DELETE RESTRICT or NO ACTION (the default): refuse the delete while orders exist.
  • ON DELETE CASCADE: delete the orders too.
  • ON DELETE SET NULL: keep the orders, clear the link.

The referenced column must be a primary key or have a unique constraint. A common surprise: PostgreSQL does not index the referencing column for you. Without an index on orders.user_id, joins are slower and every delete on users has to scan orders to check for children. Add the index yourself.

Unique

A unique constraint forbids two rows with the same value (or same combination, for UNIQUE (tenant_id, slug)). You can have as many as you need. It is how you protect business rules such as one account per email, even when two requests try to insert at the same moment, which an application-level check cannot fully guarantee.

NULL handling differs. In PostgreSQL and MySQL, several rows can have NULL in a unique column because NULL is not equal to NULL. SQL Server allows only one NULL in a unique constraint. Check your database before relying on either.

The database enforces uniqueness with an index, so a unique column is also fast to search.

Index

An index is a separate data structure, usually a B-tree, that keeps a column's values sorted with pointers to the rows. It turns "scan the whole table" into "jump to the right place". It does not change which data is allowed.

Indexes have a cost: each one takes disk space and must be updated on every insert, update and delete of the indexed columns. Index the columns you filter, join and sort on, and skip columns that are rarely queried or have very few distinct values. For multi-column indexes, order matters: an index on (user_id, created_at) helps WHERE user_id = 42 ORDER BY created_at, but not a query on created_at alone.

Common mistakes

  • Treating a unique constraint as "just an index". It is a rule. Removing it to "speed up inserts" lets duplicates in.
  • Forgetting to index foreign key columns in PostgreSQL.
  • Adding an index for every column "just in case", which slows down writes.
  • Using a natural, changeable value as the primary key.
  • Relying on application code alone to prevent duplicates or orphan rows.

When to pick which

  • Every table gets a primary key. Prefer a surrogate key unless you have a stable natural one.
  • Use a foreign key whenever a column stores another row's ID and you want the database to guarantee the link exists. Then index that column.
  • Use unique for any business rule of the form "there can only be one", including multi-column ones.
  • Use a plain index when queries are slow because they filter, join or sort on a column, and the rule about duplicates does not apply.

Watch the animated version: https://youtu.be/5tVSYe-jYUI

In short

Primary key identifies, foreign key links, unique forbids duplicates, index speeds up. The first three protect your data; the last one protects your response times.


Originally published at abdeldjalilchougui.biz.

Top comments (0)