Course contents

04. Database Fundamentals Lesson 1 of 10

Relational Databases

Tables, keys and joins, how constraints and transactions protect data, why unindexed joins and N+1 queries hurt, and when a relational database fits.

15 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Relational databases store data as tables of typed rows, linked by primary and foreign keys.
  • Normalisation stores each fact once; joins reassemble related rows at query time.
  • Constraints and transactions are enforced by the database for every writer.
  • Joins are cheap on indexed columns and expensive on unindexed ones; N+1 queries multiply round trips.
  • Relational is the default for structured, related data with integrity needs; leave it for a measured reason.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A relational database stores data in tables (relations). Each table holds rows of the same shape; each column has a type. A primary key identifies every row; a foreign key is a column whose value must match a primary key in another table, which is how rows refer to each other. You read and write with SQL, a declarative language: you describe the result, and the database's query planner decides how to get it. PostgreSQL, MySQL/MariaDB, SQL Server, Oracle and SQLite are relational; so are distributed SQL systems such as CockroachDB, YugabyteDB and Google Spanner.

Why it exists

Before the relational model (Codd, 1970), applications navigated stored records through pointers and had to know the physical layout. The relational model separated the logical view (tables and their relationships) from storage, so the same data can answer questions nobody planned for, and the layout can change without rewriting programs. Decades of engineering added what most business systems need: integrity checks, transactions, concurrency control and crash recovery.

How it works

Schema and normalisation. Data is split into tables so that every fact is stored once: the customer's email lives in customers, orders refer to the customer by customer_id. This avoids update anomalies (changing a copy in one place but not another), insert anomalies (being unable to store a product until someone orders it) and delete anomalies. Normal forms (1NF, 2NF, 3NF, BCNF) formalise this; in practice "one table per kind of thing, facts stored once" gets you most of the way.

Joins. A query that needs data from several tables joins them on matching columns. The planner chooses a join algorithm per pair using statistics about the tables:

  • Nested loop: for each row on one side, look up matches on the other, ideally through an index. Best when one side is small.
  • Hash join: build a hash table from the smaller input, probe it with the larger. Good for large unsorted inputs and equality conditions.
  • Merge join: walk two inputs sorted on the join key in step. Good when both are already sorted (for example by an index).

EXPLAIN (and EXPLAIN ANALYZE, which also runs the query) shows the plan chosen.

Constraints. PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL and CHECK are evaluated on every insert, update and delete. A write that would break one is rejected, whoever sends it.

Transactions. BEGIN … COMMIT groups statements so they succeed or fail together (atomicity), see a consistent state while other transactions run (isolation, at a configurable level), and survive a crash once committed (durability, via a write-ahead log). Together with consistency rules from constraints this is ACID.

Storage. Rows live in fixed-size pages (8 KB in PostgreSQL, 16 KB in InnoDB). Indexes, usually B-trees, map key values to rows. Writes go first to a write-ahead log, so a crash can be replayed.

When to use it

  • Structured data with relationships: users, orders, payments, inventory, bookings.
  • When correctness matters: money, stock, anything where a half-done change is a bug.
  • When you do not know all future queries: reporting, analytics on operational data, new features over existing data.
  • As the default for a new system. A single well-indexed PostgreSQL or MySQL instance handles thousands of transactions per second on modest hardware, and read replicas extend reads further.

When not to

  • Writes or data that outgrow one primary and cannot be split cleanly: consider sharding, distributed SQL or a NoSQL store designed for horizontal scale.
  • Data accessed only by key as opaque blobs (sessions, carts, feature flags): a key-value store is simpler and faster.
  • Highly variable, nested documents read and written as a whole: a document store may fit better.
  • Specialised access patterns: full-text search, deep graph traversals, high-ingest time series, vector similarity. Relational engines have extensions for several of these (PostgreSQL full-text search, pgvector, TimescaleDB), which is often enough until scale says otherwise.

Trade-offs

Choice You gain You pay
Normalised schema One source of truth, no update anomalies Joins at read time
Denormalised copies Fewer joins on hot read paths Keeping copies in sync on every write
Database-enforced constraints Integrity for every writer A little write cost; schema changes need migrations
Strict isolation (serializable) No concurrency anomalies More aborts and retries under contention
Single primary Simple consistency A ceiling on write throughput

Alternatives

  • Document databases (MongoDB, Couchbase, Firestore): nested JSON-like documents, flexible schema, good when data is read and written per aggregate.
  • Key-value and wide-column stores (DynamoDB, Cassandra, Redis): designed around known access patterns and horizontal scale.
  • Graph databases (Neo4j, Amazon Neptune): relationships as first-class data, efficient multi-hop traversals.
  • Distributed SQL (CockroachDB, YugabyteDB, Spanner): the relational model and transactions, sharded and replicated across machines, at the cost of higher write latency.

Failure modes

  • Unindexed joins and filters: fine in development, table scans in production as data grows. PostgreSQL does not index foreign-key columns automatically.
  • N+1 queries: an ORM loads related rows one query at a time; round trips and database load grow with the number of items.
  • Lock contention and deadlocks: long transactions holding locks on hot rows; the database aborts one side of a deadlock.
  • Connection exhaustion: each connection costs memory (a process per connection in PostgreSQL); many app instances need a pooler.
  • Risky migrations: adding a column with a default, building an index or adding a constraint can lock a big table unless done online (CREATE INDEX CONCURRENTLY, NOT VALID constraints validated later).
  • Primary saturation: all writes on one machine; replicas do not help writes.

In production

Index every column you join or filter on, and check plans with EXPLAIN ANALYZE. Turn on the slow query log (or pg_stat_statements) and watch for repeated statements that signal N+1. Keep transactions short. Put a connection pooler (PgBouncer, RDS Proxy, or the driver's pool) between many app instances and the database. Run schema changes as backward-compatible, online migrations. Take backups you have restored at least once, and replicate across zones for failover.

Common misconceptions

  • "Joins are slow." Joins on indexed keys are among the most optimised operations in any database; unindexed ones are slow.
  • "Relational databases don't scale." One node handles far more than most products need; replicas, partitioning and sharding take it further. They are harder to scale writes horizontally than stores designed for it.
  • "The ORM handles performance." It generates the queries you ask for, including N+1.
  • "Foreign keys always create indexes." Not in PostgreSQL.
  • "NoSQL means no schema." The schema moves into the application instead.

Interview angle

Start with a relational database unless a requirement rules it out, and say why: relationships, transactions, ad-hoc queries. Sketch the main tables with keys and the indexes for the main queries. Expect follow-ups on scaling (read replicas, caching, then partitioning or sharding by a key), on consistency (which operations need a transaction), and on when you would move a specific access pattern to another store. Naming concrete pitfalls — N+1, unindexed foreign keys, long transactions — shows production experience.

Model assumptions

The live traffic is simulated with a simple cost model: one database with 10 connections, a mean cost per query (4 ms for a key lookup, 200 ms for the join that scans order_items, 8–10 ms for index-backed joins) and per insert, lognormally distributed (cv 0.3); queries that wait more than 500 ms for a connection fail. The engine has no query planner, so a plan change is modelled as a change of query cost. The tables, the join plan, the constraint checks and the transaction with its rollback are scripted illustrations (moving packets between scenery nodes), not simulated. In the N+1 step the simulation counts queries; the page latency quoted is computed from the number of sequential round trips. Numbers are illustrative, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Data as tables with keys

    A relational database stores data in tables: rows of the same shape, with typed columns. Every row has a primary key (customers.id) that identifies it. Rows in other tables refer to it with a foreign key: orders.customer_id points at a customer, order_items points at an order and a product.

    Each fact is stored once. A customer’s email lives in one row of customers, not copied into each of their orders, so changing it is one update and nothing can disagree. Splitting data this way is called normalisation.

    The tables on the right are an illustration; the live traffic from the app tier (60 small queries per second) is simulated and keeps the database lightly loaded.

    Scene: The Shop database holds four tables: customers, orders, order_items and products. Foreign keys link orders to customers and order items to orders and products. The app tier sends 60 small queries per second; the database is lightly loaded.

    Key idea: Tables hold one kind of thing each; keys connect them, so every fact is stored exactly once.

  2. 2. A join puts the pieces back together

    The order page needs data from all four tables. The app sends one query:

    SELECT … FROM orders o JOIN customers c ON c.id = o.customer_id JOIN order_items i ON i.order_id = o.id JOIN products p ON p.id = i.product_id WHERE o.id = 81233

    The database’s query planner decides how. Here it picks a nested-loop join with index lookups: find the order by primary key, then its customer, then its three items, then their products. Four index lookups inside the database, one round trip for the app.

    The packets are a scripted illustration of that plan.

    Scene: Illustration: the app sends one query to the database, which looks up the order, its customer, its three items and their products in turn, then returns one combined result to the app.

    Key idea: You describe the result with SQL; the planner chooses how to fetch and combine the rows.

  3. 3. Constraints reject bad data at the door

    The schema is not only a description; the database enforces it on every write.

    First insert: an order item for product 999. The foreign key check finds no such product and the insert is rejected (red). Second: a new customer with an email that already exists. The UNIQUE constraint rejects it. Third: a valid item. The product exists, the row is written, the app gets its answer.

    Because the checks live in the database, every application, script and migration that writes is held to the same rules. (Scripted illustration.)

    Scene: Illustration: an insert with a missing product is rejected by the foreign key, an insert with a duplicate email is rejected by a unique constraint, and a valid insert is written.

    Key idea: Constraints (PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK) make invalid states impossible, whoever writes.

  4. 4. Transactions: all of it or none of it

    Placing an order writes three tables: a row in orders, rows in order_items, and a stock decrement in products. Wrapped in BEGIN … COMMIT, they form one transaction.

    Order 1 succeeds: three writes, then COMMIT, and the app gets one answer. Order 2 writes its order and items, but the stock update violates CHECK (stock >= 0): the product is sold out. The transaction is rolled back (PostgreSQL aborts it at the failed statement; the app issues ROLLBACK): the order and item rows are discarded as if they had never been written, and the app gets an error. No half-placed orders, no negative stock.

    Concurrent transactions are kept apart by the isolation level; that is its own lesson. (Scripted illustration.)

    Scene: Illustration: the first order writes orders, order items and products and commits. The second order fails the stock check, its order and item rows are rolled back and the app receives an error.

    Key idea: A transaction makes several writes atomic: either all become visible at commit, or none do.

  5. 5. A join without an index

    Traffic grows to 80 queries per second. One second in, a new "order history" page ships; it joins orders with order_items on order_id. In PostgreSQL a foreign key does not create an index on the referencing column (MySQL’s InnoDB does), and nobody added one.

    For every order the planner now has to scan order_items. In this model the query costs 200 ms instead of 4 ms. Eighty of those per second need more than the 10 connections can give: queries wait, and those that wait over 500 ms fail.

    Scene: Traffic rises to 80 queries per second. One second in, the main query starts scanning order_items and takes about 200 ms. The database saturates, queries wait for connections and some fail.

    Key idea: Joins are cheap when the join columns are indexed, and table scans when they are not.

  6. 6. Index the foreign key

    CREATE INDEX ON order_items (order_id). One second in, the index is ready and the planner switches back to index lookups. In this model the query drops from 200 ms to about 8 ms, a little more than before because the history page joins more rows.

    The backlog clears and errors stop. Inserts into order_items now also maintain that index, a small price for a join every page uses.

    Scene: One second in, an index on order_items.order_id is ready. The query takes about 8 ms, the backlog clears and nothing fails.

    Key idea: Index the columns you join and filter on; foreign keys are usually among them.

  7. 7. N+1: the join done in the application

    A refactor moves the page to an ORM that loads lazily: one query for the customer’s 20 orders, then one query per order for its items. That is 21 queries per page instead of one join.

    Each query is small (4 ms), but 80 pages per second become 1,680 queries per second. The database spends most of its time on per-query overhead and is now about two-thirds busy for the same pages it served at under 10%.

    The page waits for 21 sequential round trips: about 21 × (4 ms + 6 ms network) ≈ 210 ms, against about 10 + 6 = 16 ms for one join. That page latency is computed, not simulated; the simulation counts queries, so its P95 shows per-query time.

    Scene: The application now issues 21 queries per page, 1,680 queries per second in total. Each is fast, but the database is about two-thirds busy.

    Key idea: Loading related rows one query at a time multiplies round trips and database work; let the database join.

  8. 8. Back to one query

    Eager loading (JOIN or WHERE order_id IN (…)) fetches the orders and their items in one query. In this model it costs about 10 ms.

    The database drops back to under 10% busy, and the page is one round trip again. ORMs make N+1 easy to write and hard to see; look for it in query logs (the same statement repeated with different ids) and in tracing.

    Scene: The application loads orders and items in one query again: 80 queries per second, and the database is under 10% busy.

    Key idea: Fewer, set-based queries beat many tiny ones: that is what a relational engine is built for.

  9. 9. When a relational database fits

    Choose a relational database when your data has relationships you query in different ways, when correctness matters (money, stock, bookings), and when you do not yet know every future query: SQL and joins let you ask new questions of the same data.

    It fits less well when one machine cannot hold the write load or data (you then shard, or pick a distributed SQL or NoSQL store), when records are schemaless blobs fetched only by key, or for specialised access such as full-text search, graphs with deep traversals or time series at very high ingest.

    Scene: The Shop database with its four related tables serves the app tier with one query per page, lightly loaded.

    Key idea: Relational is the default for structured, related data with integrity needs; move away for a specific, measured reason.