A relational database stores data in tables made of rows and columns, links tables together with keys, and lets you ask questions with a language called SQL. Its most valuable feature is the transaction: a group of changes that either all happen or none happen, even if the server crashes halfway.
In an interview, "which database?" is usually your first storage decision. To answer well you need to know what a relational database gives you for free (joins, constraints, transactions) and where it starts to hurt (one machine has a ceiling). This lesson covers the model, the four ACID guarantees, isolation levels, and the numbers that tell you when one relational database is enough.
Detailed Notes
What is it?
A relational database (RDBMS) organises data into tables. A table has columns (the fields, each with a type) and rows (one record each). Examples are PostgreSQL, MySQL and SQL Server.
Three ideas matter:
Primary key (PK). A column (or set of columns) that uniquely identifies a row, such as user_id. The database refuses duplicates.
Foreign key (FK). A column that points to the primary key of another table, such as orders.user_id pointing to users.user_id. The database refuses a value that does not exist in the target table. This is how relationships are stored.
Join. A query that combines rows from two tables by matching keys: "give me each order together with the name of the user who placed it".
You talk to the database with SQL (Structured Query Language), a declarative language: you describe what you want, and the database decides how to fetch it.
Three Related TablesData model
usersRelational DB
PKuser_idbigint
UQemailvarchar(255)
no duplicates
namevarchar(100)
ordersRelational DB
PKorder_idbigint
FKuser_idbigint
must exist in users
statusvarchar(16)
IDXcreated_attimestamp
for date queries
One row per order.
order_itemsRelational DB
FKorder_idbigint
FKproduct_idbigint
quantityint
unit_pricedecimal(10,2)
price at purchase time
Many items per order. unit_price is copied on purpose: later price changes must not rewrite history.
orders.user_idusers.user_id· many to one
order_items.order_idorders.order_id· many to one
Key point. Each fact is stored once. A join reassembles it at read time.
Foreign keys connect orders to users and order_items to orders and products.
Normalization in one paragraph
Normalization means storing each fact exactly once. The user's name lives in users, not copied into every order. If the user changes their name, you update one row and every order shows the new name. The price you pay is joins at read time. In an interview, say: "I'll normalise by default and denormalise (copy data) only where a measured read path needs it."
Why do we need it?
Money, inventory, bookings and accounts share two properties: the data has relationships, and mistakes are expensive. Consider a bank transfer of $100 from account A to account B. It needs two writes: subtract from A, add to B. If the server crashes between them, $100 disappears. Application code cannot reliably fix this by itself, because it cannot know what the database had already saved when the crash happened.
A relational database solves the problem once, inside the database: you wrap the writes in a transaction and the database guarantees the outcome. It also enforces rules (a foreign key must exist, an email must be unique) so a bug in one service cannot quietly corrupt data used by ten others.
How does it work?
ACID: the four guarantees of a transaction
A transaction is a group of reads and writes treated as one unit. You mark it with BEGIN, and end it with COMMIT (keep everything) or ROLLBACK (undo everything).
text
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 'A';
UPDATE accounts SET balance = balance + 100 WHERE id = 'B';
COMMIT;
ACID is the name for what a transaction promises:
Atomicity. All or nothing. If the second update fails, the first is undone. There is never a half-finished transfer.
Consistency. A transaction moves the database from one valid state to another. Rules such as "balance >= 0" or "this foreign key must exist" are checked, and a transaction that would break them is rejected. (This is the database's rule-checking, not the same word as "consistency" in the replication lessons.)
Isolation. Transactions running at the same time do not see each other's unfinished work. It should look as if they ran one after another.
Durability. Once COMMIT returns, the data survives a crash or power loss. The database achieves this by first appending the change to a write-ahead log (WAL), a sequential file on disk, and flushing it before it says "committed". After a crash it replays the log.
An Atomic Transfer That Rolls BackRequest flow
Key point. Atomicity moves the all-or-nothing logic out of your code and into the database.
The debit is undone because the credit failed. Money is never lost.
Isolation levels: the knob you can turn
Perfect isolation is expensive, because it forces transactions to wait for each other. So databases offer isolation levels, each allowing fewer odd behaviours (called anomalies) at a higher cost.
Dirty read. You read another transaction's change before it commits, and it then rolls back. You acted on data that never existed.
Non-repeatable read. You read a row twice in one transaction and get different values because someone committed a change in between.
Lost update. Two transactions read a balance of 100, both add 10, and both write 110. One addition is lost.
Phantom. You run the same query twice and a new matching row appears.
Level
Prevents
Typical use
Read committed
Dirty reads
Default in PostgreSQL. Fine for most reads.
Repeatable read
Dirty and non-repeatable reads
Reports that must see one stable snapshot.
Serializable
All of the above, including lost updates and phantoms
Money, inventory, seat booking. Slowest; may abort and ask you to retry.
Two techniques stop the lost update without full serializable isolation:
Row lock.SELECT ... FOR UPDATE locks the row; the second transaction waits until the first finishes.
Optimistic concurrency. Store a version number. Update with WHERE id = 7 AND version = 3 and set version = 4. If zero rows change, someone else won; reload and retry.
Interview tip. A common mistake is saying "SQL is ACID so it's always correct". The default isolation level (read committed) still allows lost updates. If your design has a read-modify-write (read a value, change it, write it back), say which lock or version check protects it.
Where one machine runs out
A single well-tuned relational server comfortably handles roughly these numbers (rule-of-thumb figures to state as assumptions, not guarantees):
text
Storage : about 1-2 TB per node before backups and maintenance get painful
Simple reads/s : about 10,000-20,000 on one node with good indexes
Writes/s : about 2,000-5,000 on one node
Connections : a few hundred; each costs memory
Example: an e-commerce site has 5 million orders a year at 2 KB each = 10 GB a year. Peak traffic is 300 orders per second. That is far below the limits, so one primary database plus a read replica for failover is enough for years. Many systems never leave this stage, and saying so shows judgment.
When a limit is crossed you have a ladder, in this order: add indexes (next-but-one lesson), add a cache, add read replicas (copies that serve reads), and only then shard (split the data across machines, covered in the partitioning lesson). Sharding is the expensive step because a transaction touching two shards is no longer simple.
Real-world example
A food-delivery app stores customers, restaurants, orders and payments. When a customer pays, the system must (1) create the order, (2) mark the payment as captured, and (3) decrement the dish's remaining stock. These three writes go in one transaction. If the stock update fails because the dish just sold out, the order and payment rows are rolled back automatically and the customer sees "item unavailable" instead of being charged for nothing. A report that lists "orders with restaurant name and city" is a join of orders, restaurants and cities and runs in one query.
System design example
Design the ticket-purchase part of an event site. The access patterns are: look up an event, list its remaining seats, and buy a seat exactly once. Requirements: no seat may be sold twice, and a payment must not be taken for a seat that is gone.
Store events, seats (with status and event_id FK) and orders in a relational database.
Buy a seat in one transaction: UPDATE seats SET status='sold', order_id=? WHERE seat_id=? AND status='available'. If it changes zero rows, someone else got the seat, so return 409 Conflict. The WHERE status='available' check makes the update safe even under read committed, because the database locks the row while updating.
Scale: 10,000 events x 5,000 seats x 100 bytes = 5 GB. Peak 1,000 purchases per second is a burst, absorbed by a queue or by sharding by event_id later.
Notice what drove the choice: relationships plus multi-row correctness, not the size of the data.
Interview discussion. Say it like this: "Seats and orders are related and money is involved, so I want transactions and constraints. The data is only a few GB, so a single relational primary with a replica is enough. I'd shard by event only if write volume outgrows one node."
Trade-off thinking. A relational database gives strong guarantees and flexible queries, but it scales writes vertically first, and cross-shard transactions are hard. Choose it when correctness and relationships matter more than unlimited write scale. A NoSQL store (next lesson) flips that trade.
Key interview takeaway
Default to a relational database when data has relationships and correctness matters. Name the guarantee you need (atomic multi-row update, unique constraint, isolation against lost updates) and the mechanism that provides it. Show that you know the scaling ladder: index, cache, replicas, then shard.
Real World Example
A food-delivery app records an order, a payment and a stock decrement in one transaction, so a sold-out dish rolls back the whole purchase instead of charging the customer.