SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Relational Databases
  • Document Databases
  • Key-Value Databases
  • Full-Text Search Engines
  • Wide Column Databases
  • Time Series Databases
  • Graph Databases
  • Vector Databases
  • NewSQL Databases
  • Columnar Databases
  • In-Memory Databases
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Types (Deep Dive)

Relational Databases

Tables, rows, keys and joins: the classic way to store connected data (PostgreSQL, MySQL).

⏱ 14 min readBeginnerMust KnowHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A relational database stores data in tables. A table has rows (one record each) and columns (one fact each). Tables are linked by keys, and you ask questions with SQL.

  • Each fact is stored once, and other tables point to it with a foreign key.
  • A join puts the pieces back together when you read.
  • It gives strong guarantees (ACID transactions) and a fixed schema. PostgreSQL and MySQL are the usual examples.

02Concept: What is it?

Think of a spreadsheet with strict rules. Every row in a table has the same columns, and each column has a type (number, text, date). One column, the primary key, is unique for each row, so you can always find exactly one row.

Real data is connected. A customer has many orders. An order has many items. Instead of copying the customer details onto every order, we keep a customers table and an orders table. An order stores only a customer_id. That column is a foreign key: it must match a real row in the other table. This way of splitting data is called normalization.

Two tables linked by a key
customers
πŸ”‘id (primary key)1, 2, 3 ...
πŸ‘€name, cityAsha, Pune
←customer_id points to id
orders
πŸ”‘id (primary key)101, 102 ...
πŸ”—customer_id (foreign key)1, 1, 2 ...
πŸ“¦item, price
The order does not copy the customer. It only points to the customer's id.
🧠The three big ideas
Schema (the shape is declared up front), relations (keys connect tables) and transactions (a group of changes either all happens or none of it does).

03Real-Life Example

🍡The Library Card Catalogue
A library keeps one card for each member and one card for each loan. The loan card does not repeat the member's address. It only writes the member number. If a member moves house, the librarian fixes one card, and every loan is still correct. To find a member's loans, the librarian looks up the number and walks through the loan cards.
Library
Relational database
A drawer of member cards
A table (customers)
One card
One row
The member number
Primary key
Member number written on a loan card
Foreign key
Walking from loan cards to member cards
A join
Fix the address on one card only
Normalization: one fact, one place
Rule: cannot lend to an unknown member
Foreign key constraint
Finding a card by number, using the sorted drawer
An index
A read with a join
πŸ§‘β€πŸ’»AppSELECT ... JOIN
→↓SQL
🧠Query plannerchooses a plan
→↓index lookups
πŸ—‚οΈcustomers
πŸ—‚οΈorders
→↓matched rows
πŸ“„Result

04Why Do We Need It?

πŸ”—Connected data
Customers, orders and products link to each other in a clean way.
πŸ›‘οΈCorrectness
Types, unique keys and foreign keys stop bad data from getting in.
πŸ’³Transactions
Money moves out of one account and into another, or nothing happens.
πŸ”ŽFlexible questions
SQL can answer questions you did not plan for when you designed the tables.
✏️Easy updates
A fact stored once is changed once. No copies to forget.
🧰Mature world
Decades of tools, drivers, backups, monitoring and experts.
If your data has clear relationships and you care about being right, start with a relational database.

05Where Do We Use It?

🏦Banking and payments
Accounts, ledgers and transfers need strict correctness.
πŸ›’E-commerce
Users, products, carts, orders and stock.
πŸ₯Booking and records
Seats, appointments, patients, inventory.
🏒Business apps
HR, CRM and ERP systems, full of linked records.
πŸ“ˆReports
Group, sum and join many tables to make dashboards.
🌱Most new products
A single PostgreSQL or MySQL is a very good default to start with.

06Types / Parts / How It Works

The main pieces

PieceWhat it isExample
Table, row, columnThe grid that holds the data.customers(id, name, city)
Primary keyA column (or columns) that is unique for each row.id
Foreign keyA column that must match a primary key in another table.orders.customer_id
IndexAn extra sorted structure that finds rows fast, usually a B-tree.index on orders(customer_id)
JoinCombines rows of two tables where keys match.INNER JOIN, LEFT JOIN
ConstraintA rule the database enforces for you.NOT NULL, UNIQUE, CHECK
TransactionA group of changes that is all or nothing (ACID).BEGIN ... COMMIT

Relationship shapes

ShapeMeaningHow it is stored
One to oneA user has one profile.Foreign key with a unique rule, or the same primary key.
One to manyA customer has many orders.Foreign key on the "many" side.
Many to manyStudents and courses.A third "join table" with two foreign keys.
Normalized
Split into tables
  • Each fact stored once
  • Updates are safe and small
  • Reads need joins
  • Good for writes and correctness
Denormalized
Copied into one table
  • Reads need no join
  • Many copies to keep in sync
  • Bigger storage
  • Good for read-heavy reports
Scaling a relational database
✍️Primarytakes writes
→↓replicate
πŸ“–Replica 1reads
πŸ“–Replica 2reads
Writes Reads
Scaling up is easy. Scaling out takes more thought. We cover these in later topics.
VisualizerNormalized tables vs one flat tableSwitch between the two layouts, then run each action. Drag the slider to give the customer thousands of orders and see what an update costs.
How is the data stored?
What do you run?
Which customer?
SELECT o.id, o.item, c.name, c.city FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.id = ?
customers (primary key: id)
idnamecity
1AshaPune
2BenLeeds
3ChenOslo
orders (foreign key: customer_id)
idcustomer_iditemprice
1011Book$12
1021Pen$3
1032Lamp$30
1041Mug$8
1053Desk$120
1062Cable$5
Highlighted rows are the ones the query touches. The sample shows 3 of this customer's orders. The numbers below use the slider.
Rows read
51
Rows written
0
Bad row accepted?
n/a
Cells in sample
33
flat repeats the name and city
The join matches customer 1 (Asha) with every order that has customer_id = 1. It reads 51 rows for 50 orders. The price: the database must do the matching work.

A simplified cost model: it counts rows touched, not milliseconds. Real databases use indexes, so a join on a foreign key is usually fast. The point is where each fact is stored and who guards it.

07How to Use It / Steps / Implementation

Designing a relational schema

  1. 1
    List the things (entities)
    Customers, orders, products. Each usually becomes a table.
  2. 2
    Pick a primary key for each
    A simple id is common. Keep it stable. Do not use something that can change, like an email.
  3. 3
    Connect them with foreign keys
    Put the key on the "many" side. Use a join table for many-to-many.
  4. 4
    Choose column types and rules
    Use NOT NULL, UNIQUE and CHECK so the database guards the data.
  5. 5
    Write down your top queries
    Then add indexes for the columns you filter and join on.
  6. 6
    Wrap related writes in a transaction
    Order plus stock change plus payment should succeed or fail together.
  7. 7
    Measure and tune
    Use EXPLAIN to see the plan. Denormalize only where the numbers show you need to.
A small example (SQL)
CREATE TABLE customers (
  id   BIGINT PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT
);

CREATE TABLE orders (
  id          BIGINT PRIMARY KEY,
  customer_id BIGINT NOT NULL REFERENCES customers(id),
  item        TEXT NOT NULL,
  price       NUMERIC(10,2) NOT NULL
);
CREATE INDEX idx_orders_customer ON orders(customer_id);

SELECT o.id, o.item, c.name
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE c.id = 1;
πŸ’‘Index your foreign keys
A join on an un-indexed foreign key makes the database scan the whole table. An index on orders.customer_id turns that into a quick lookup. (PostgreSQL does not create it for you.)

08Key Terms to Know

TermMeaning in easy words
Table, row, columnA grid of data. A row is one record. A column is one field
SchemaThe declared shape of the tables, columns and types
Primary keyA unique id for each row in a table
Foreign keyA column that points to a row in another table and is checked by the database
JoinCombining rows from two tables where a key matches
SQLThe language used to ask the database questions and change data
NormalizationSplitting data so each fact is stored once
IndexA sorted helper structure that finds rows fast
TransactionA group of changes that happens fully or not at all
ACIDAtomicity, Consistency, Isolation, Durability: the transaction promises
Query plannerThe part that decides how to run a query (which index, which join order)
MigrationA script that changes the schema safely over time

09Pros, Cons and Trade-offs

βœ… Pros
  • Strong consistency and ACID transactions
  • Powerful, flexible queries with SQL
  • Data rules enforced by the database
  • Very mature tools and skills
  • Great for connected data
⚠️ Cons
  • Schema changes need planning on big tables
  • Joins across huge tables can be slow
  • Scaling writes across many machines is harder (needs sharding)
  • Fixed shape suits messy or fast-changing data less
  • Object code and tables do not always match (the "object-relational mismatch")

Trade-offs

ChoiceWe gainWe lose
Normalize moreClean data, small updatesMore joins on reads
DenormalizeFaster, simpler readsCopies to keep in sync, risk of mismatch
More indexesFaster readsSlower writes, more disk
Strong isolationSafer resultsMore locking or retries, less throughput
Single primarySimple and consistentOne machine takes all the writes
Read replicasMore read capacityReplicas can lag behind (stale reads)

10Common Problems and Mistakes

Common mistakes

  1. Missing indexes. Queries scan millions of rows. Most slow apps start here.
  2. The N+1 query. The app loads 100 orders, then runs 100 more queries for each customer. Use a join or a batch.
  3. SELECT * everywhere. It moves data you do not need.
  4. Over-indexing. Every index slows each write.
  5. Long transactions. They hold locks and block others.
  6. Risky migrations. Adding a column with a default, or an index, can lock a big table on some versions. Test first.
  7. Using it as a queue or a cache. Other tools do these jobs better.

Things to watch

πŸ”ŒConnections
Each connection costs memory. Use a pool (see Connection Pooling).
πŸ•°οΈReplica lag
A read just after a write may not see it on a replica.
🧱Hot tables
One huge table needs partitioning or sharding sooner or later.
πŸ’ΎBackups
Test restores. A backup you never restored is only a hope.

11Real-World Examples

🐘PostgreSQL
Open source, rich features (JSON, extensions, strong SQL). Used by many companies as a main database.
🐬MySQL
A very popular open-source database behind many web apps. Large sites have run it at huge scale, often with sharding.
☁️Managed services
Amazon RDS and Aurora, Google Cloud SQL, Azure SQL run backups, failover and replicas for you.
🌍Distributed SQL
Systems such as Google Spanner, CockroachDB and YugabyteDB keep SQL and transactions across many machines.
πŸ“±SQLite
A tiny embedded relational database in phones and browsers.
🏒Commercial engines
Oracle and SQL Server run many large business systems.
πŸ“Note
These are general ideas. Features and limits vary by product and version.
Mini case: an online shop
πŸ›’Shop app
→↓
πŸ—„οΈPostgreSQLusers, orders, stock
⇒⇣changes
πŸ”Search index
⚑Cache
Orders and payments sit in the relational database. Other data goes to tools that fit it better.

12Related Topics to Read Next

Common Database Types→

Where relational databases sit among the other kinds.

SQL vs NoSQL→

When to pick relational, and when not to.

ACID Transactions→

The guarantees that make relational databases trustworthy.

Indexing→

How a query finds rows without reading the whole table.

Denormalization→

When to break normalization on purpose for fast reads.

Sharding→

How to spread a relational database over many machines.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: tables of rows and columns, linked by keys, queried with SQL.
  • βœ”Keys: primary key identifies a row. Foreign key points to another table and is checked.
  • βœ”Normalize: store each fact once. Join to read. Denormalize only with proof.
  • βœ”Guarantees: schema, constraints and ACID transactions.
  • βœ”Speed: add indexes on filter and join columns. Use EXPLAIN.
  • βœ”Scale: scale up, add replicas for reads, then partition or shard.
  • βœ”Watch: N+1 queries, missing indexes, long transactions, replica lag.
  • βœ”One line: β€œConnected data, strong rules: store each fact once and let keys link it.”
← Previous
Write-Ahead Log (WAL)
Next β†’
Document Databases