DatabasesVol. 4 · Part IV
0 / 0

Shelves / Databases

DB·00

Start Here: What a Database Is

For readers who have never used a database: why files aren't enough, what a database guarantees, a first PostgreSQL session explained line by line, the kinds of databases and when each fits, how this volume is organised, and how to study it.

11 topics · ~10 min read · 10-question quiz
Updated Suggest a correction

Start here: how to use this volume

Two reading paths

This volume covers how data is modelled, queried, stored, protected and scaled: the relational model and SQL, PostgreSQL in depth, storage engines, transactions, query optimisation, scaling, NoSQL stores, search, and backups. Every chapter has the same shape: a plain-language Start here section with small, verified examples; a How deep to go ladder; the full-depth sections; a Lab of real measured experiments; and a Revision sheet.

  • New to databases? Read this chapter, then the chapters in order. Run every example (PostgreSQL is free and installs in minutes), answer Check yourself before opening the answers, and take each quiz.
  • Experienced? Skip this chapter. In each chapter read the revision sheet first and take its quiz, then use How deep to go to choose which internals sections and lab experiments to study.

Mastery levels

Every chapter uses the same six levels:

Level Name You can… Example for indexes
L1 Recognition define it and spot it "that query needs an index"
L2 Working use it correctly add the right B-tree index for a WHERE clause
L3 Internals explain why it works explain how a B-tree finds a row in four page reads
L4 Debugging diagnose failures read EXPLAIN ANALYZE and find why the index isn't used
L5 Design choose between approaches decide between a composite index, a partial index and a materialised view
L6 Production run it at scale build indexes on a live 2 TB table without blocking writes

What a database is

Why not just a file?

Every program that keeps data could write it to a file. Here's what happens when a café's ordering system does exactly that, storing orders in a JSON file, with four processes taking orders at the same time:

Python
def place(n):
    for i in range(200):
        with open("orders.json") as f: orders = json.load(f)      # read everything
        orders.append({"customer": n, "i": i})                    # change it
        with open("orders.json", "w") as f: json.dump(orders, f)  # write everything back
Text
1) 4 processes x 200 orders appended to a JSON file: file is corrupt: JSONDecodeError
2) after a crash mid-write, all 50,000 old orders are unreadable: JSONDecodeError - Unterminated string starting at: line 1 column 629632

Two disasters. First, concurrency: processes read the file while another was halfway through rewriting it, and overwrote each other's changes, ending in a file that isn't even valid JSON (on other runs it's valid but missing hundreds of orders). Second, crashes: a process that died a third of the way through rewriting the file destroyed not just its own change but every order ever saved. Now the same work through PostgreSQL:

Text
3) the same 4 x 200 orders through PostgreSQL: 800 orders
4) a process deletes everything, inserts 50,000 rows, then dies before COMMIT: table still has 800 orders

Every order arrived, and the half-finished work of the crashed process vanished as if it had never started. That's what a database is for: a program that stores data and guarantees its integrity while many clients read and write it at once and while machines crash. The guarantees have a name, ACID:

  • Atomicity: a transaction's changes happen completely or not at all (experiment 4).
  • Consistency: rules you declare (unique names, positive prices, valid references) always hold.
  • Isolation: concurrent transactions don't see each other's half-done work (experiment 3).
  • Durability: once the database says "committed", the data survives a crash or power cut.

On top of that, a database gives you a query language to ask questions of the data without writing loops, and indexes that make those questions fast on billions of rows.

ApplicationSELECT … / INSERT … PostgreSQL backend process Parser Planner Executor text → tree → plan → rows (chapter 60) Shared buffer cache (8 KB pages) Data files (heap, indexes) WALwritten first one connection= one process
What happens to one SQL query inside PostgreSQL. The client sends text; the server parses and plans it, the executor reads pages through the shared buffer cache, and changes are recorded in the write-ahead log before they are acknowledged.

Your first database

Tools you need

  • PostgreSQL 16 or later (the most widely used open-source relational database, and this volume's main example): install it from your package manager, Postgres.app on macOS, the EDB installer on Windows, or run docker run -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:18.
  • psql, its command-line client (installed with it), or a graphical client such as DBeaver, pgAdmin or DataGrip.
  • For later chapters: Python with psycopg, Redis, and SQLite (built into Python). Each lab says what it uses.

A café database in twenty lines

SQL
CREATE TABLE dish (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name        text   NOT NULL UNIQUE,
  category    text   NOT NULL,
  price_paise int    NOT NULL CHECK (price_paise > 0)
);
CREATE TABLE order_line (
  order_id bigint NOT NULL,
  dish_id  bigint NOT NULL REFERENCES dish(id),
  qty      int    NOT NULL CHECK (qty > 0)
);
INSERT INTO dish (name, category, price_paise) VALUES
  ('Masala dosa', 'breakfast', 9000), ('Idli', 'breakfast', 5000), ('Vada', 'breakfast', 4000),
  ('Thali', 'lunch', 18000), ('Filter coffee', 'drinks', 3000);
INSERT INTO order_line VALUES (1, 1, 2), (1, 5, 2), (2, 4, 1), (3, 1, 1), (3, 2, 2), (3, 5, 3);

A table has a fixed set of named, typed columns; each row is one dish or one order line. The primary key (id) identifies each row, generated automatically. Constraints are rules the database enforces on every write: NOT NULL, UNIQUE, CHECK, and the foreign key REFERENCES dish(id), which guarantees every order line points at a real dish. Money is stored as integer paise, never floating-point (Volume 1 chapter 6).

SQL
SELECT name, (price_paise / 100.0)::numeric(8,2) AS rupees
FROM dish WHERE category = 'breakfast' ORDER BY price_paise DESC;
Text
    name     | rupees
-------------+--------
 Masala dosa |  90.00
 Idli        |  50.00
 Vada        |  40.00
SQL
SELECT d.name, sum(l.qty) AS sold, (sum(l.qty * d.price_paise) / 100.0)::numeric(10,2) AS revenue
FROM order_line l JOIN dish d ON d.id = l.dish_id
GROUP BY d.name ORDER BY revenue DESC;
Text
     name      | sold | revenue
---------------+------+---------
 Masala dosa   |    3 |  270.00
 Thali         |    1 |  180.00
 Filter coffee |    5 |  150.00
 Idli          |    2 |  100.00

SQL is declarative: you describe the result (which rows, joined how, grouped by what, in what order) and the database decides how to compute it. The second query joins two tables on matching ids and aggregates per dish; Vada doesn't appear because nobody ordered it (chapter 56 shows how an outer join would include it).

The database says no

Text
INSERT INTO dish (name, category, price_paise) VALUES ('Idli', 'breakfast', 4500);
ERROR:  duplicate key value violates unique constraint "dish_name_key"
DETAIL:  Key (name)=(Idli) already exists.

INSERT INTO dish (name, category, price_paise) VALUES ('Free lunch', 'lunch', 0);
ERROR:  new row for relation "dish" violates check constraint "dish_price_paise_check"

INSERT INTO order_line VALUES (4, 99, 1);
ERROR:  insert or update on table "order_line" violates foreign key constraint "order_line_dish_id_fkey"
DETAIL:  Key (dish_id)=(99) is not present in table "dish".

These rules hold no matter which application, script or person writes to the database, and no matter how many write at once. Application code can (and should) validate too, for friendlier messages, but only the database can guarantee them.

Fast at any size: indexes

A table of 2 million orders, and a question about one customer:

Text
SELECT count(*) FROM big_orders WHERE customer = 'cust4242';     Time: 68.141 ms     (reads every row)
CREATE INDEX ON big_orders(customer);                             Time: 1871.378 ms   (built once)
SELECT count(*) FROM big_orders WHERE customer = 'cust4242';     Time: 0.923 ms      (looks it up)

Without an index the database must scan all 2 million rows; with one it jumps straight to the 20 matching rows, about 70× faster here and the gap grows with the table. An index is a separate sorted structure (usually a B-tree, chapter 58) mapping values to row locations, like the index at the back of a book. Indexes speed up reads and slow down writes slightly, so you add them for the queries you actually run (chapter 60).

The kinds of databases

Relational databases are the default for business data, but other designs exist for workloads they serve poorly. Chapter 62 compares them in depth:

Kind Data looks like Good at Examples
Relational Tables with typed columns, joined by keys Transactions, flexible queries, integrity PostgreSQL, MySQL, SQL Server, Oracle, SQLite
Document JSON-like documents Nested, variable-shape records read as a whole MongoDB, Couchbase, PostgreSQL jsonb
Key-value Opaque values by key Very fast lookups, caching, sessions Redis, Valkey, DynamoDB, RocksDB
Wide-column Rows of sparse columns, partitioned Huge write volumes across many machines Cassandra, ScyllaDB, Bigtable
Graph Nodes and relationships Traversing connections Neo4j, Neptune
Search Inverted indexes over text Relevance-ranked full-text search Elasticsearch, OpenSearch, Meilisearch
Vector Embeddings Similarity ("semantic") search pgvector, Qdrant, Milvus
Analytical Columns, not rows Aggregations over billions of rows ClickHouse, DuckDB, BigQuery, Snowflake
Time-series Timestamped measurements Metrics, IoT, retention and downsampling TimescaleDB, InfluxDB, Prometheus

A good default for a new product: PostgreSQL for the system of record, plus specialised stores only when a measured need appears.

How to study databases

A routine that works

  1. Read one topic of a Start here section.
  2. Run every query yourself, and change one thing before running it again: a filter, an index, a row count.
  3. Look at the plan: put EXPLAIN ANALYZE in front of any query that interests you, and read what the database actually did.
  4. Break it on purpose: open two psql sessions and make them conflict; kill a process mid-transaction; fill a table with ten million rows.
  5. Answer Check yourself without looking, take the quiz, and revisit a few days later.

Warm-up exercises

Before chapter 55, extend the café database:

  1. Add an orders table (id, customer name, placed_at timestamp, status) and make order_line.order_id a foreign key to it.
  2. Write a query listing every dish with how many times it was ordered, including dishes never ordered (with 0).
  3. Find each order's total in rupees, and the most expensive order.
  4. Try to delete a dish that appears in an order. What happens, and how would ON DELETE options change it?
  5. In two psql windows, start a transaction in each (BEGIN;), update the same dish's price in both, and see what the second one does until the first commits.

Glossary

  • Database / DBMS: the stored data / the software managing it (PostgreSQL is a DBMS).
  • Table, row, column: a relation, one record, one typed attribute.
  • Primary key: a column (or columns) uniquely identifying each row.
  • Foreign key: a column that must match a primary key in another table.
  • Constraint: a rule the database enforces on every write.
  • Transaction: a group of statements committed or rolled back as one unit.
  • Index: a structure that finds rows by value without scanning the table.
  • Query plan: the steps the database chose to compute a query's result.