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_idsays "this book's author is row N ofauthors". The database rejects a book whoseauthor_idpoints at no author. - Constraints such as
NOT NULLare 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.