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 VALIDconstraints 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.