The Complete Read on Keys: Primary, Foreign and Composite

Keys are what turn a pile of tables into a connected database. This chaptered read gathers everything a beginner needs about them in one place, with a tiny example in each chapter. Read it online; nothing to download.

Chapter 1: what a key is for

A key is a column, or a set of columns, that identifies rows. Keys let you say "this exact row" without ambiguity, and they let one table point to another.

Chapter 2: primary keys

Every table should have one primary key. Its rules:

CREATE TABLE books (
  id     INTEGER PRIMARY KEY,
  title  TEXT NOT NULL
);

Chapter 3: natural or made-up keys?

A natural key is a real-world value, such as a book's ISBN or a country code. A surrogate key is a value invented by the database, such as 1, 2, 3.

KindExampleProsCons
NaturalISBN, country codeMeaningfulReal-world values can change or be missing
SurrogateAuto-numbered idSimple, stableMeans nothing by itself

Beginners usually do well with surrogate keys, plus a UNIQUE constraint on natural values that must not repeat:

CREATE TABLE countries (
  id    INTEGER PRIMARY KEY,
  code  TEXT NOT NULL UNIQUE,
  name  TEXT NOT NULL
);

Chapter 4: foreign keys

A foreign key is a column that points to the primary key of another table:

CREATE TABLE reviews (
  id       INTEGER PRIMARY KEY,
  book_id  INTEGER NOT NULL REFERENCES books(id),
  stars    INTEGER CHECK (stars BETWEEN 1 AND 5)
);

Now the database refuses a review for a book that does not exist. In SQLite, turn enforcement on with PRAGMA foreign_keys = ON; for each connection.

Chapter 5: what happens on delete

If a book is deleted, what about its reviews? You can choose:

Choose deliberately; cascading deletes are convenient but can remove more than you expect.

Chapter 6: composite keys

Sometimes a row is identified by two columns together. A link table between students and courses is the classic case:

CREATE TABLE enrolments (
  student_id  INTEGER NOT NULL REFERENCES students(id),
  course_id   INTEGER NOT NULL REFERENCES courses(id),
  PRIMARY KEY (student_id, course_id)
);

The pair must be unique, so a student cannot enrol in the same course twice.

Chapter 7: unique keys

A table has one primary key but can have several unique constraints, for example on email and on username. These are sometimes called candidate or alternate keys: they could identify a row, but you chose another column as the primary key.

Chapter 8: a checklist

For practice, try picking a good primary key and the follow-up questions beginners ask next.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

This page is a free outline. No downloadable files, paid content, courses or certificates are offered on this site.