Primary and Foreign Keys

The two constraints that stop a database from holding rows that cannot be true. Try to break them and watch the insert be refused.

Primary and Foreign Keys

query.sql SQLite
Result

Worth knowing

A primary key is two promises in one: the value is unique, and it is never NULL.
A foreign key says this column's value must already exist in another table's key column.
The database enforces both on every write. Application code that checks first still has a race; the constraint does not.
SQLite needs PRAGMA foreign_keys = ON. Most engines enforce them by default.

Overview

A primary key is a column or set of columns whose values uniquely identify each row and cannot be NULL. A table has one primary-key constraint, though it may contain several columns. A good key is stable and actually unique in the modeled data. SQLite has a historical exception: some non-integer primary-key declarations in ordinary rowid tables can accept NULL. Declare such columns NOT NULL explicitly or use a STRICT or WITHOUT ROWID table when relying on the rule.

In this guide
  1. A primary key identifies a row
  2. A foreign key enforces a reference
  3. Composite keys and design
  4. Optional references and uniqueness
  5. Further reading

A primary key identifies a row

A surrogate key such as an integer ID is convenient when no natural identifier is both unique and stable. Natural keys can still be useful as UNIQUE constraints. A surrogate ID does not make other real-world uniqueness rules disappear.

A foreign key enforces a reference

A foreign key says that a value in one table must match a candidate key in another table, or be NULL if the relationship is optional.

query.sqlSQLite
Result

This prevents an order from referring to a customer row that does not exist. ON DELETE and ON UPDATE actions determine what happens when the referenced row changes; choose RESTRICT, CASCADE, or SET NULL to match the domain.

In SQLite, foreign-key enforcement must be enabled for each connection with PRAGMA foreign_keys = ON unless configured otherwise. Some engines do not automatically index the child-side foreign-key column, so add an index when joins or parent updates need it.

Composite keys and design

A composite key uses more than one column when identity is only unique in combination, such as (course_id, student_id) in an enrollment table. If referencing it, the foreign key must include the same key columns. See normalization and constraints.

Optional references and uniqueness

A nullable foreign key can represent an optional relationship, but decide whether NULL means “not assigned yet” or “not applicable.” A UNIQUE constraint on a natural identifier may permit multiple NULL values in SQLite and PostgreSQL, so combine it with NOT NULL when every row must have an identifier. Composite keys can prevent duplicate pairs such as the same student enrolling twice in one course. They also enlarge foreign keys and indexes that carry the pair. Choose clarity and stability over minimizing the number of columns.

Further reading

Check yourself

0 of 3

Answer without scrolling back up.

  1. What two guarantees does declaring a primary key give you?

  2. Why is a surrogate integer usually preferred over an email address as a primary key?

  3. Why does SQLite in particular need `PRAGMA foreign_keys = ON`?

Cheat sheet

Primary and Foreign Keys

Define a primary key and a foreign key, attempt an insert that violates each, and watch the database enforce referential integrity for you.

DATABASE · vizlearn.in/database/primary_and_foreign_keys.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.