← SQL and databases

Choosing good keys

Why every table gets an id.

Start this lesson

Every table needs a primary key that never repeats and never is NULL. Names make poor keys: two members can be called Ana Souza, and people change their names. That is why most tables get a simple id number that means nothing except "this row". Other tables then point to that id.

CREATE TABLE authors (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  country TEXT
);

The id identifies the author; the name is just information about them and is allowed to repeat or change.

A primary key should also be stable. If it changed, every row in other tables pointing to it would have to change too.