Skip to the workspace
Pebellslearn by building
Relational Databases  ›  Lesson

Tables, Rows and Keys

PostgreSQL 14 minA relational database stores data in tables of rows, gives each row a primary key, and links tables with foreign keys instead of copying data.

backend / Tables, Rows and Keys

Explore each scene at your own pace.

01 · The rule

The rule

Tables, Rows and Keys

The bookshop needs to remember its books, its authors and every order, and still have them tomorrow after a restart. Variables in your program vanish when it stops. A database keeps data safe on disk, lets many requests read and write it at once, and refuses data that breaks your rules.

The rule

One thing per row, one key per row, link tables by key.

A relational database, such as PostgreSQL, stores data in tables. Each table holds one kind of thing; each row is one of those things; each column is one fact about it, with a fixed type.

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

CREATE TABLE books (
  id        INTEGER PRIMARY KEY,
  title     TEXT NOT NULL,
  price     INTEGER NOT NULL,          -- in rupees
  author_id INTEGER NOT NULL REFERENCES authors(id)
);
  • A primary key identifies exactly one row. No two books share an id, and it is never empty.
  • A foreign key stores another table's primary key to link rows. books.author_id says "this book's author is row N of authors". The database rejects a book whose author_id points at no author.
  • Constraints such as NOT NULL are rules the database enforces for you, whatever code sends the data.

To bring the linked pieces back together, you join on the key:

SELECT books.title, authors.name
FROM books
JOIN authors ON authors.id = books.author_id;

Why not just store the author's name in every book row? Because then one fact lives in many places. Fix a misspelling in one row and miss another, and the database now holds two versions of the truth. Linking by key keeps each fact in one place.

Relational databases also run changes in transactions: a group of statements that either all succeed or all fail. "Create the order and reduce the stock" never half-happens.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.