Skip to content
Commitwise
Menu
Databases

How relational databases work

Tables, rows and primary keys, how foreign keys model one-to-many and many-to-many relationships, which constraints keep data valid, and what a database does with your SQL. The foundations under every SQL, JPA, Room and Core Data question.

beginner

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

An online shop keeps its orders in a JSON file. It works for a month. Then two requests save at the same moment and one order disappears. Someone deletes a customer, and their orders now point at nobody. “Show me every order over $100” reads the whole file and takes four seconds.

A relational database exists to solve exactly these problems. Every backend talks to one (PostgreSQL, MySQL, SQL Server, Oracle), and every mobile app carries one: Room on Android and Core Data on iOS both run on SQLite. This section uses one small shop database throughout: customers, products, orders and the items in each order. The SQL is PostgreSQL’s, with notes where MySQL or SQLite differ.

New to some of these? Open what you need, or skip ahead.

Basics:What is a database?

A database is a program that stores data and answers questions about it. You don’t read its files yourself: you send it a request (“save this order”, “give me this customer’s orders”) and it does the work. It keeps the data safe when the app crashes, lets many users work at once, and finds what you ask for quickly, even among millions of records.

Basics:What is SQL?

SQLSQLThe language for defining, querying and changing data in a relational database.Open in glossary → (Structured Query Language, said “S-Q-L” or “sequel”) is the language you use to talk to a relational database. One statement creates a table, another adds a row, another asks a question:

SELECT name FROM customers WHERE country = 'RS';

You describe what you want, not how to find it. The database decides how.

Part Not started

Tables, rows and keys

A table looks like a spreadsheet, but it’s much stricter. Each column has a name and a type, and the database refuses values that don’t fit. Each row is one thing: one customer, one product, one order.

Every table needs a way to point at exactly one row. That’s the primary keyPrimary keyThe column (or columns) that uniquely identifies each row of a table; never empty, never repeated.Open in glossary →: a column whose value is unique and never empty. Think of a student ID card. Two students can share a name, but never an ID. Most tables use a number that the database generates for you.

The types you’ll use most:

TypeHoldsExample
integer, bigintwhole numbersids, quantities
text, varchar(100)stringsnames, emails
numeric(10, 2)exact decimalsprices, money
booleantrue or falseis_active
date, timestamptza day, a moment in timebirthday, created_at

A few rules you can attach to a column, called constraints:

  • NOT NULL: the column must always have a value.
  • UNIQUE: no two rows may have the same value.
  • DEFAULT: the value to use when an insert doesn’t give one.
  • PRIMARY KEY: unique and not null, the row’s identity.

A table is a set of rows with a fixed, typed schema; the database enforces types and constraints on every write, which is the main thing an app gets over a file or a key-value store. Choices that matter in interviews and in production:

  • Keys. A surrogate key (a generated bigint or UUID) is the default; a natural key (email, ISBN, country code) is fine only when it truly never changes. Put a UNIQUE constraint on natural identifiers anyway. Use GENERATED ALWAYS AS IDENTITY (SQL standard, PostgreSQL 10+) instead of the older serial; MySQL uses AUTO_INCREMENT, SQLite’s INTEGER PRIMARY KEY is the rowid.
  • Money. numeric(p, s) or integer cents. Never real/double precision: binary floats can’t represent 0.10 exactly.
  • Time. timestamptz stores an instant (normalized to UTC) and converts on display; timestamp without a zone stores whatever wall-clock value you give it, which breaks when servers or users are in different zones.
  • Strings. In PostgreSQL text and varchar(n) perform the same; varchar(n) only adds a length check. Case-insensitive uniqueness needs a unique index on lower(email) or the citext type.
  • Constraints are concurrency-safe. Checking “does this email exist?” in app code and then inserting races under load; a UNIQUE constraint can’t.

Predict the output

The email column is UNIQUE. Two inserts run one after the other with the same email. What happens?

INSERT INTO customers (email, name) VALUES ('ana@example.com', 'Ana');
INSERT INTO customers (email, name) VALUES ('ana@example.com', 'Ana Petrović');
CREATE TABLE customers (
    id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email      text NOT NULL UNIQUE,
    name       text NOT NULL,
    country    char(2),                              -- may be empty (NULL)
    created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE products (
    id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name      text NOT NULL,
    price     numeric(10, 2) NOT NULL CHECK (price >= 0),
    stock     integer NOT NULL DEFAULT 0 CHECK (stock >= 0),
    is_active boolean NOT NULL DEFAULT true
);

The price that doesn’t add up

Spot the bugA cart total that's off by a fraction of a cent

Tap the line with the bug.

CREATE TABLE cart_items (
    id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    cart_id  bigint NOT NULL,
    price    real NOT NULL,
    quantity integer NOT NULL
);

SELECT sum(price * quantity) FROM cart_items WHERE cart_id = 7;

Deep diveChoosing a primary key: bigint, UUIDv4 or UUIDv7Interview favorite

bigint identity: 8 bytes, new values always go to the right edge of the index, so inserts are cheap and pages stay full. Downsides: ids are guessable (/orders/1001 invites trying 1002, an IDORIDOR (Insecure Direct Object Reference)A security bug where the server returns or changes an object just because the client knows its id, without checking that the caller owns it.Open in glossary → risk if authorization is weak), they leak volume, and they need the database to generate them, which complicates merging data from offline clients or several databases.

UUIDv4: 16 bytes, random, generated anywhere (a phone can create the id offline). Randomness is the problem: each insert lands on a random page of the B-tree index, so a big table touches cold pages, splits them and bloats the index and the write-ahead log.

UUIDv7: 16 bytes, the first 48 bits are a millisecond timestamp, so new ids are roughly increasing like a sequence while still being generated anywhere. PostgreSQL 18 has uuidv7(); elsewhere you generate them in the app. It reveals the creation time, which is usually fine.

A common answer: bigint internally, plus a separate random public id (or UUIDv7) for URLs and APIs. Whatever you choose, never reuse ids and never change a primary key value, because other tables point at it.

  • Surrogate bigint GENERATED ALWAYS AS IDENTITY (or UUIDv7) as the primary key; natural identifiers get their own UNIQUE.
  • Money: numeric or integer cents, never floats. Time: timestamptz. PostgreSQL text = varchar(n) in speed.
  • Constraints (NOT NULL, UNIQUE, CHECK) are enforced on every write and are race-free; app-side checks aren’t.
  • UUIDv4 keys scatter inserts across the index; UUIDv7 and sequences append.
CREATE TABLE customers (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL,
    price numeric(10, 2) CHECK (price >= 0),
    created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX customers_email_lower ON customers (lower(email));

Check this part

  1. What makes a column a good primary key?

  2. Which type should a price column use?

  3. Why does app code that checks "email exists?" before inserting still allow duplicates?

  4. Why are random UUIDv4 primary keys slow to insert into a large table?

Data lives in tables: each column has a name and a strict type, each row is one thing. A primary key identifies each row; NOT NULL, UNIQUE and DEFAULT keep values valid. Store money as numeric or integer cents, never as a float.

Part Not started

Relationships and foreign keys

An order belongs to a customer. Instead of copying the customer’s name and email into every order, the order stores the customer’s id. That column is a foreign keyForeign keyA column that points at a row in another table, and that the database keeps valid.Open in glossary →: a pointer from a row in one table to a row in another.

The database guards the pointer. It refuses:

  • an order for customer 42 when there is no customer 42, and
  • deleting a customer who still has orders (unless you say what should happen to them).

So the data can’t end up pointing at nobody, which is exactly what broke the JSON file.

There are three shapes of relationship:

  • One-to-many. One customer has many orders. The foreign key goes on the “many” side: orders.customer_id.
  • Many-to-many. An order has many products, and a product appears in many orders. Neither table can hold the other’s id, so you add a third table in between, often called a junction table: order_items, one row per product in an order.
  • One-to-one. One user has one profile. It’s a foreign key that is also UNIQUE, and it’s rare: usually those columns just go in the same table.

order_items also stores unit_price. That looks like a copy of products.price, but it isn’t: it’s the price at the moment of purchase. When the product’s price changes next week, old orders must still show what the customer paid.

Foreign keys give referential integrity: the database checks them on every insert, update and delete, inside the same transaction, so no code path (a script, a second service, a bug) can create orphans. What to decide:

  • ON DELETE. NO ACTION/RESTRICT (the default) rejects deleting a referenced parent; CASCADE deletes children too; SET NULL keeps them unlinked. CASCADE suits true parts of the parent (order → order items), never independent history (customer → orders). Many systems soft-delete instead (deleted_at), which keeps history and keeps the foreign keys valid.
  • Indexes. PostgreSQL indexes the referenced side (the primary key) but not the referencing column. Without an index on orders.customer_id, every join by customer and every parent delete scans orders. MySQL’s InnoDB creates that index automatically.
  • Junction tables. A composite primary key (order_id, product_id) prevents duplicate lines and serves lookups by order; add an index on product_id for the reverse direction. Use a surrogate id instead when the same pair may legitimately appear twice or the row is referenced elsewhere.
  • Historical values like unit_price are deliberate denormalization: a fact at a point in time, not a duplicate.
  • Limits. Foreign keys stop at the database boundary. Across microservices or shards, integrity becomes the application’s job (events, reconciliation, sagas).

Predict the output

Customer 1 has three orders. orders.customer_id references customers(id) with no ON DELETE option. What does this statement do?

DELETE FROM customers WHERE id = 1;
CREATE TABLE orders (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id bigint NOT NULL REFERENCES customers (id),
    status      text NOT NULL DEFAULT 'NEW',
    total       numeric(10, 2) NOT NULL DEFAULT 0,   -- sum of its items, kept for fast lists
    created_at  timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_id ON orders (customer_id);

-- many-to-many between orders and products
CREATE TABLE order_items (
    order_id   bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
    product_id bigint NOT NULL REFERENCES products (id),
    quantity   integer NOT NULL CHECK (quantity > 0),
    unit_price numeric(10, 2) NOT NULL,          -- the price paid, not today's price
    PRIMARY KEY (order_id, product_id)
);
CREATE INDEX order_items_product_id ON order_items (product_id);

Practice: model a library

Exerciseeasy

Books, authors and loans

A library app needs to store:

  • books (title, year),
  • authors (name); a book can have several authors and an author writes many books,
  • members (name, email, unique),
  • loans: which member borrowed which book, when, and when it came back (empty while it’s still out).

Write the CREATE TABLE statements with primary and foreign keys.

›

Books and authors are many-to-many. What sits between them?

›

A member can borrow the same book many times, so a loan needs its own id.

SolutionTry it yourself first
CREATE TABLE books (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title text NOT NULL,
    year  integer
);

CREATE TABLE authors (
    id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL
);

CREATE TABLE book_authors (                      -- junction table
    book_id   bigint NOT NULL REFERENCES books (id),
    author_id bigint NOT NULL REFERENCES authors (id),
    PRIMARY KEY (book_id, author_id)
);

CREATE TABLE members (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name  text NOT NULL,
    email text NOT NULL UNIQUE
);

CREATE TABLE loans (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    book_id     bigint NOT NULL REFERENCES books (id),
    member_id   bigint NOT NULL REFERENCES members (id),
    borrowed_at timestamptz NOT NULL DEFAULT now(),
    returned_at timestamptz                      -- NULL while the book is out
);

book_authors uses the pair as its primary key, so the same author can’t be added to a book twice. loans gets its own id, because the same member and book appear together again on every new loan.

Deep diveThe delete that locked the orders tableInterview favorite

A support tool deletes a test merchant. products.merchant_id references merchants with ON DELETE CASCADE, and order_items.product_id references products. Two things go wrong at once:

  1. No index on the referencing columns. For each deleted product, PostgreSQL must check order_items for rows that still point at it. Without an index on order_items.product_id, that’s a full scan per product: 3,000 products × a 40-million-row table. The statement runs for an hour.
  2. Cascades are one transaction. Every cascaded row is deleted and locked inside the same transaction, the write-ahead log grows by gigabytes, replicas fall behind, and concurrent writes to those rows wait.

What to say in an interview: index every foreign key column you join or delete through; use CASCADE only for rows that are truly part of the parent; delete big trees in batches (children first, a few thousand rows per transaction); and prefer soft deletes or archiving for business data that has history.

  • Foreign keys = referential integrity checked inside every transaction. They stop at the database boundary (services, shards).
  • Default ON DELETE rejects deleting a referenced row; CASCADE only for owned children; soft delete for business history.
  • PostgreSQL doesn’t index foreign key columns for you (InnoDB does). Missing ones make joins and parent deletes scan.
  • Junction table with composite primary key plus an index on the second column; copy historical values like unit_price on purpose.

Check this part

  1. One customer has many orders. Where does the foreign key go?

  2. How do you store that an order contains many products and a product is in many orders?

  3. Deleting a customer in PostgreSQL is slow, though customers is small. What is the usual cause?

  4. When is ON DELETE CASCADE a good choice?

A foreign key points from a row to a row in another table, and the database refuses links to rows that don't exist. One-to-many puts the foreign key on the many side; many-to-many needs a junction table. Choose ON DELETE behavior on purpose and index foreign key columns.

Part Not started

What the database does with your SQL

SQL is declarative: you say what you want and the database works out how. When you send a query, three things happen:

  1. Parse. The database checks the SQL is valid and that the tables and columns exist.
  2. Plan. The planner chooses how to get the answer: read the whole table, or jump to the rows through an indexDatabase indexA sorted structure on one or more columns that lets the database find rows without reading the whole table.Open in glossary →, and in which order to combine tables. For the same query it may pick different plans as the data grows.
  3. Execute. It runs the plan and sends back the rows.

The data itself lives on disk in small blocks called pages (8 KB in PostgreSQL), and the pages you use often stay cached in memory. That’s why the same query is slow the first time and fast the second.

What you get over a JSON file:

Problem with a fileWhat the database does
Two saves at once lose oneMany users work at once; each change is a transaction that happens completely or not at all
A crash in the middle of a save corrupts itEvery change goes to a log first, so committed data survives a crash
Orders pointing at deleted customersConstraints and foreign keys reject bad data
Finding rows reads everythingIndexes and the planner find rows fast

Those guarantees have a name, ACIDACIDAtomic, Consistent, Isolated, Durable: the guarantees a database transaction gives.Open in glossary →: Atomic, Consistent, Isolated, Durable. The Transactions lesson in this section covers them in detail.

On mobile, the database is SQLite: not a server, but a library inside your app that keeps everything in one file. Room (Android) and Core Data (iOS) write the SQL for you, but the tables, keys and indexes underneath are the same ideas.

The pipeline: parser → rewriter (views, rules) → planner/optimizer → executor. The planner is cost-based: it estimates row counts from statistics (ANALYZE, run automatically by autovacuum) and picks scan types (sequential, index, index-only, bitmap) and join algorithms and order. Stale statistics and correlated columns cause bad estimates, which cause bad plans; EXPLAIN (ANALYZE, BUFFERS) compares estimated and actual rows.

Storage: heap tables in 8 KB pages, B-tree indexes pointing to row locations, a shared buffer cache on top of the OS cache. Durability comes from the write-ahead logWrite-ahead logA log where the database records every change before applying it, so committed data survives crashes.Open in glossary →: a commit returns once its WAL record is flushed; data pages are written later by checkpoints, and replicas replay the same WAL. Concurrency in PostgreSQL is MVCCMVCCMulti-version concurrency control: writers create new row versions so readers never wait for them.Open in glossary →: an update writes a new row version, readers see a snapshot and don’t block writers, and VACUUM removes dead versions later (bloat comes from long transactions holding old snapshots).

Statement categories you may be asked to name: DDL (CREATE, ALTER, DROP), DML (SELECT, INSERT, UPDATE, DELETE), DCL (GRANT, REVOKE), TCL (BEGIN, COMMIT, ROLLBACK). In PostgreSQL DDL is transactional too, so a failed migration rolls back cleanly; in MySQL most DDL commits implicitly.

Client-server vs embedded: PostgreSQL runs a process per connection, so backends use a connection pool. SQLite runs in-process with one writer at a time; WAL mode lets readers proceed during a write, which Room enables by default.

Predict the output

The customers table has no index besides its primary key. Which order do the names come back in?

SELECT name FROM customers;
EXPLAIN SELECT * FROM customers WHERE email = 'ana@example.com';

-- Index Scan using customers_email_key on customers  (cost=0.29..8.30 rows=1 width=64)
--   Index Cond: (email = 'ana@example.com'::text)

EXPLAIN SELECT * FROM customers WHERE name = 'Ana';

-- Seq Scan on customers  (cost=0.00..2041.00 rows=3 width=64)
--   Filter: (name = 'Ana'::text)

Worked example: one query, two plans

The email column is UNIQUE, so PostgreSQL built an index for it automatically. The name column has no index. Here is what happens to each query from the plan above, in a table of 100,000 customers.

  1. Parse. Both queries are valid: customers, email and name exist.
  2. Plan the email query. The planner knows there is a sorted index on email and that at most one row can match. Walking the index takes about three page reads, so it picks an Index Scan.
  3. Plan the name query. There is no index on name. The only way is to read every page of the table and check each row: a Seq Scan (sequential scan). Its statistics guess that about 3 rows are named Ana.
  4. Execute. The email query reads a handful of pages; the name query reads all of them, about 1,000 pages. Fine for 100,000 rows, slow for 100 million.
  5. Fix if needed. If the app searches by name often, CREATE INDEX customers_name ON customers (name); and run EXPLAIN again. The Indexes lesson goes deeper.
Deep diveWhy every backend needs a connection poolInterview favorite

Each PostgreSQL connection is a separate OS process with its own memory (several MB, more with big work_mem sorts). Opening one costs a TCP handshake, TLS, authentication and a fork, often several milliseconds. max_connections defaults to 100, and raising it to thousands hurts throughput: the server spends its time switching between processes and contending on locks instead of running queries.

So applications keep a small pool of open connections and lend them to requests: HikariCP in Spring Boot (default 10), or a proxy like PgBouncer in transaction mode in front of many app instances or serverless functions. Sizing rule of thumb: a few connections per CPU core of the database, not per request; extra requests wait for a free connection, which is better than overloading the database.

Follow-up questions: holding a connection during a slow HTTP call starves the pool (keep transactions short); with transaction-mode PgBouncer, session state like SET and advisory locks doesn’t carry over between transactions; and virtual threads make thousands of concurrent requests cheap but don’t make the database accept thousands of connections, so the pool size, not the thread count, becomes the limit.

  • Parse → plan (cost-based, uses statistics from ANALYZE) → execute. Bad estimates make bad plans; check with EXPLAIN (ANALYZE, BUFFERS).
  • WAL gives durability and replication; MVCC row versions mean readers don’t block writers and VACUUM cleans up.
  • DDL/DML/DCL/TCL; PostgreSQL DDL is transactional, MySQL’s mostly isn’t.
  • No ORDER BY, no order. Process per connection: always pool (HikariCP, PgBouncer).

Check this part

  1. What does it mean that SQL is declarative?

  2. A query has no ORDER BY. In which order come the rows?

  3. What makes a committed transaction survive a crash in PostgreSQL?

  4. Why not give each of 2,000 concurrent requests its own PostgreSQL connection?

SQL is declarative: the database parses it, the planner picks a plan using statistics and indexes, and the executor runs it. Data lives in pages cached in memory; the write-ahead log makes commits durable. ACID transactions, concurrency and constraints are what you get over a file. Rows have no order without ORDER BY.

Key takeaways

  • A table has typed columns and one row per thing; the primary key identifies each row and never changes.
  • Constraints (NOT NULL, UNIQUE, CHECK) and foreign keys stop bad data at the door. Money is numeric or cents, never real.
  • One-to-many puts the foreign key on the many side; many-to-many needs a junction table.
  • SQL says what you want; the planner decides how. Rows have no order without ORDER BY.
  • Room and Core Data run on SQLite, with the same tables, keys and indexes.
  • Surrogate keys by default (sequence or UUIDv7), UNIQUE on natural identifiers, constraints over app-side checks.
  • Index foreign key columns in PostgreSQL; use CASCADE only for owned children, batch big deletes, soft-delete history.
  • Cost-based planner + statistics, WAL for durability and replication, MVCC for concurrency.
  • Process-per-connection means pooling; keep transactions short so connections return quickly.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.