basics02Chapter 2 of 6

Keys

How does the database know which row is which, and how does an order know who placed it? With keys.

The primary key

Every table should have a column that tells its rows apart: the primary key. In the Byte Shop it is always id. No two rows may share a value, and it is never empty.

Why a number and not the name?

  • Names repeat: there can be two Anna Beckers.
  • Names change: people marry, products get renamed.
  • Values go missing: Ben has no e-mail address, so the e-mail cannot be the key.
  • A short number is quick to compare and easy to store in other tables.
customersTry it in SQLiteSQLite

Two inserts into the four customers below. They run in real SQLite, on a fresh copy every time.

idINTEGERnameTEXT
1Anna Becker
2Ben Okafor
3Chiara Rossi
4Deniz Kaya

Pick one of the two inserts.

The foreign key

An order has to say who placed it. It does not copy the customer's name and city; it stores the customer's id in its column customer_id. A column that holds another table's primary key is a foreign key.

Click an order. The line shows which customer its customer_id points at.

orders.customer_id → customers.id

orders

customers

1Anna Becker
2Ben Okafor
3Chiara Rossi
4Deniz Kaya

Order 7 has customer_id 1, so it belongs to Anna Becker.

Excerpt: customers 1 to 4 and five orders from January

Why not write the name into every order? Then a new address would have to be changed in many places, and sooner or later one copy is out of date. With a key, each fact lives in one place.

In the Byte Shop's schema the link is written down like this:

customer_id INTEGER NOT NULL
    REFERENCES customers (id)