skipnothing/SQL

Primary & Foreign Keys

Three rows sit in users: Ada, Brent, Cleo. An order arrives carrying user_id = 2, which user does it point at, and what stops one arriving with user_id = 99 for a user who doesn't exist?

  • ▸The arrow between two tables isn't documentation, it's a rule the database checks on every write.
  • ▸Delete a row with children pointing at it: blocked, swept along, or left with NULL, you choose at declaration time.
  • ▸Ada changes her email: an auto-id stays still; the email as identifier means every row pointing at her must change.
BUILDS ON
01

The Primary Key, One Column That Identifies

Look at users: three rows of (id, name, email). The id column has a different value in every row, no row has it blank. Ask the database to treat this column as the row's identity, name it the primary key, and the table makes two guarantees automatically. First, no two rows may share an id. Second, no row may carry no id at all.

Both guarantees fall out of the word *identify*. Two rows with the same identifier aren't two rows, they're a contradiction, the database can't tell them apart. A row with no identifier is a row nothing can point at. Try to insert (1, 'Dee', 'dee@x.example') while user 1 already exists, the engine rejects it. Try (NULL, 'Dee', 'dee@x.example'), also rejected. The error fires at insert time, the row never lands.

Every table in this curriculum will declare one column this way. The column doesn't have to be id, it doesn't even have to be an integer, but whatever the column, the table commits to it carrying the row's identity from now on. A table may declare at most one primary key, the choice is singular by definition, only one column (or one fixed set of columns) gets to play the identity role.

SNEAK IN A SECOND ADA

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL
The Relational Model0/4#2 Types & NULL
#4 Normalization