Database Systems
How databases work and how to choose one: relational, NoSQL, columnar and graph engines, transactions, storage internals, ER modelling and normal forms.
1. What a Database Management System Does
A database management system (DBMS) is software that stores data and lets many users read and change it safely and fast. Compared with files, it adds five things data engineers rely on every day:
| Capability | What it means | Without it |
|---|---|---|
| Query language | Ask questions declaratively (SQL); the optimiser finds the fast way | Hand-written loops over files |
| Concurrency control | Many users read and write at once without corrupting data | Lost updates, half-written records |
| Recovery | Committed data survives crashes (write-ahead log) | Corrupted files after a power cut |
| Integrity | Types, keys, constraints reject bad data | Bad data discovered weeks later |
| Security | Users, roles, grants, auditing | Everyone sees everything |
| Term | Meaning |
|---|---|
| Schema | The structure: tables, columns, types, constraints |
| Primary key | Column(s) uniquely identifying a row |
| Foreign key | Column referencing another table's key; enforces relationships |
| Index | A data structure that finds rows without scanning everything |
| Transaction | A unit of work that succeeds or fails as a whole |
| OLTP / OLAP | Many small transactions vs few large analytical queries |
2. Types of Databases, with Real Use Cases
There is no best database, only the best fit for an access pattern. Modern systems combine several ("polyglot persistence"): a relational database for orders, a cache for sessions, a search engine for product search, a warehouse for analytics.
| Type | Data model | Examples | Real-world use | Avoid when |
|---|---|---|---|---|
| Relational (RDBMS) | Tables, rows, joins, SQL, ACID | PostgreSQL, MySQL, Oracle, SQL Server | Banking transactions, orders, inventory, ERP | Massive write scale with flexible schemas |
| Document | JSON-like documents | MongoDB, Couchbase, Cosmos DB | Product catalogues with varying attributes, user profiles, content | Many cross-entity joins and transactions |
| Key-value | Key → value | Redis, DynamoDB, Memcached | Sessions, carts, caching, rate limits, feature flags | Ad-hoc queries on values |
| Wide-column | Rows with flexible column families, partitioned by key | Cassandra, HBase, Bigtable | Time-ordered events at huge write volume: IoT, messaging | Joins, ad-hoc analytics |
| Columnar (analytical) | Columns stored separately, compressed | Snowflake, BigQuery, Redshift, ClickHouse, DuckDB | Dashboards, aggregations over billions of rows | Row-by-row OLTP updates |
| Graph | Nodes and edges | Neo4j, Amazon Neptune | Fraud rings, recommendations, network and supply-chain analysis | Simple tabular reporting |
| Time-series | Timestamped measurements | TimescaleDB, InfluxDB, Timestream | Metrics, sensors, market ticks with retention and downsampling | General-purpose relational data |
| Search | Inverted indexes | Elasticsearch, OpenSearch | Full-text product search, log analytics | System of record |
| Vector | Embeddings with similarity search | pgvector, Pinecone, Milvus, Weaviate | Semantic search and RAG for LLMs | Exact-match lookups |
| NewSQL / distributed SQL | SQL and ACID across many nodes | CockroachDB, Spanner, YugabyteDB | Global, strongly consistent OLTP | Small single-region apps (cost and complexity) |
Same data, two shapes: relational vs document
CREATE TABLE product_docs AS SELECT * FROM (VALUES
(1, '{"name": "Laptop", "attrs": {"ram_gb": 16, "cpu": "i7"}}'),
(2, '{"name": "T-shirt", "attrs": {"size": "M", "colour": "blue"}}')) t(id, doc);
SELECT id,
json_extract_string(doc, '$.name') AS name,
json_extract(doc, '$.attrs.ram_gb') AS ram_gb,
json_extract_string(doc, '$.attrs.size') AS size
FROM product_docs;| id | name | ram_gb | size |
|---|---|---|---|
| 1 | Laptop | 16 | NULL |
| 2 | T-shirt | NULL | M |
Each document carries only the attributes it needs, which is why catalogues with very different product types suit a document model. A relational design would need an attribute table or many nullable columns.
CAP and PACELC: the distributed trade-off
When a distributed database suffers a network partition, it must choose consistency (refuse some requests) or availability (answer, possibly with stale data): the CAP theorem. PACELC adds that even with no partition there is a trade-off between latency and consistency. Banking ledgers choose consistency (Spanner, CockroachDB); shopping carts and social feeds often choose availability and low latency (Cassandra, DynamoDB by default).
"I choose the database by access pattern: relational for transactions and joins, document for flexible entities, key-value for caching and lookups, wide-column for huge write volumes by key, columnar for analytics, graph for relationships, time-series for metrics, search and vector engines for text and semantic search. In distributed systems I make the CAP and PACELC trade-off explicit."
3. ACID Properties
| Property | Guarantee | Implemented by |
|---|---|---|
| Atomicity | All statements of a transaction succeed, or none do | Undo log / rollback |
| Consistency | A transaction moves the database from one valid state to another; constraints always hold | Constraints, triggers, application rules |
| Isolation | Concurrent transactions do not see each other's partial work | Locks or MVCC snapshots |
| Durability | Once committed, data survives crashes | Write-ahead log flushed to disk, replication |
Atomicity and consistency: a money transfer
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE accounts (id TEXT PRIMARY KEY, balance INT CHECK (balance >= 0))")
con.executemany("INSERT INTO accounts VALUES (?, ?)", [("A", 100), ("B", 50)])
con.commit()
def transfer(src, dst, amount):
try:
with con: # one transaction: commit or roll back
con.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", (amount, dst))
con.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (amount, src))
print(f"transfer {amount}: committed")
except sqlite3.IntegrityError as e:
print(f"transfer {amount}: rolled back ({e})")
print(" balances:", dict(con.execute("SELECT id, balance FROM accounts ORDER BY id")))
transfer("A", "B", 30) # fine
transfer("A", "B", 500) # would make A negative: CHECK fails, B's credit is undone tootransfer 30: committed
balances: {'A': 70, 'B': 80}
transfer 500: rolled back (CHECK constraint failed: balance >= 0)
balances: {'A': 70, 'B': 80}
In the failed transfer, B was credited first; the CHECK constraint then failed on A, and atomicity rolled back B's credit as well. Money was neither created nor lost.
Durability
On commit, the database writes the change to a sequential write-ahead log (WAL) and flushes it to disk before confirming. Data pages are written later. After a crash, recovery replays the log: committed changes are redone, uncommitted ones are undone. Replication to another machine or zone adds durability against losing the whole server.
"ACID means a transaction is all-or-nothing, keeps every constraint valid, is isolated from concurrent work, and survives crashes once committed. Atomicity and durability come from undo and write-ahead logs, isolation from locks or MVCC, and consistency from constraints plus application rules."
4. Isolation Levels and Concurrency
| Anomaly | What happens |
|---|---|
| Dirty read | Reading another transaction's uncommitted change, which may be rolled back |
| Non-repeatable read | Reading the same row twice in one transaction gives different values |
| Phantom read | Re-running a range query returns new rows inserted by others |
| Lost update | Two transactions read, modify and write the same row; one overwrite is lost |
| Write skew | Two transactions read overlapping data and make writes that together break a rule |
| Level | Dirty read | Non-repeatable | Phantom | Typical default |
|---|---|---|---|---|
| Read uncommitted | Possible | Possible | Possible | Rarely used |
| Read committed | Prevented | Possible | Possible | PostgreSQL, Oracle, SQL Server |
| Repeatable read | Prevented | Prevented | Possible (prevented in PostgreSQL) | MySQL InnoDB |
| Serializable | Prevented | Prevented | Prevented | Strictest; may abort transactions to retry |
Most modern databases use MVCC (multi-version concurrency control): writers create new row versions and readers see a consistent snapshot, so readers do not block writers. Lakehouse formats (Delta, Iceberg) do the same at table level with snapshots and optimistic commits.
Lost update, and two fixes
import sqlite3, os, tempfile
path = os.path.join(tempfile.mkdtemp(), "shop.db")
setup = sqlite3.connect(path)
setup.execute("CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INT, version INT)")
setup.execute("INSERT INTO stock VALUES ('X1', 10, 1)"); setup.commit()
a = sqlite3.connect(path, isolation_level=None) # two independent sessions
b = sqlite3.connect(path, isolation_level=None)
# Both read qty=10, both "sell" in application code, both write back: one sale disappears
qa = a.execute("SELECT qty FROM stock WHERE sku='X1'").fetchone()[0]
qb = b.execute("SELECT qty FROM stock WHERE sku='X1'").fetchone()[0]
a.execute("UPDATE stock SET qty=? WHERE sku='X1'", (qa - 3,))
b.execute("UPDATE stock SET qty=? WHERE sku='X1'", (qb - 2,))
print("read-modify-write:", a.execute("SELECT qty FROM stock").fetchone()[0], "(should be 5)")
# Fix 1: let the database do the arithmetic atomically
a.execute("UPDATE stock SET qty=10")
a.execute("UPDATE stock SET qty = qty - 3 WHERE sku='X1'")
b.execute("UPDATE stock SET qty = qty - 2 WHERE sku='X1'")
print("atomic update: ", a.execute("SELECT qty FROM stock").fetchone()[0])
# Fix 2: optimistic locking with a version column
a.execute("UPDATE stock SET qty=10, version=1")
va = a.execute("SELECT qty, version FROM stock").fetchone()
vb = b.execute("SELECT qty, version FROM stock").fetchone()
ok_a = a.execute("UPDATE stock SET qty=?, version=version+1 WHERE sku='X1' AND version=?", (va[0]-3, va[1])).rowcount
ok_b = b.execute("UPDATE stock SET qty=?, version=version+1 WHERE sku='X1' AND version=?", (vb[0]-2, vb[1])).rowcount
print("optimistic: A updated", ok_a, "row, B updated", ok_b, "rows -> B must re-read and retry")read-modify-write: 8 (should be 5) atomic update: 5 optimistic: A updated 1 row, B updated 0 rows -> B must re-read and retry
Pessimistic locking (SELECT ... FOR UPDATE in PostgreSQL, MySQL and Oracle) is a third fix: the second session waits until the first commits. Optimistic locking suits low contention; pessimistic suits hot rows.
"Isolation levels trade correctness for concurrency: read committed prevents dirty reads, repeatable read prevents non-repeatable reads, serializable prevents all anomalies. Most engines use MVCC so readers don't block writers. For lost updates I use atomic UPDATE expressions, optimistic locking with a version column, or SELECT FOR UPDATE on hot rows."
5. Database Architecture: How an Engine Works Inside
client (SQL)
|
QUERY PROCESSOR parser -> rewriter -> optimiser (cost-based plan) -> executor
|
TRANSACTION MANAGER lock manager / MVCC, isolation, deadlock detection
|
STORAGE ENGINE
buffer pool (cache of data pages in memory)
access methods: B-tree indexes, heap tables, LSM trees
write-ahead log (sequential, flushed on commit) --> recovery
data files on disk (pages of 8-16 KB)
| Component | Role |
|---|---|
| Parser and optimiser | Turn SQL into a plan; choose join order, join algorithm and index use from statistics |
| Executor | Runs the plan: scans, joins (nested loop, hash, merge), sorts, aggregates |
| Buffer pool | Keeps hot pages in memory; most reads never touch disk |
| WAL | Makes commits durable cheaply with sequential writes |
| Lock manager / MVCC | Provides isolation between concurrent transactions |
Row stores vs column stores
| Row store (OLTP) | Column store (OLAP) | |
|---|---|---|
| Layout | All columns of a row together | Each column stored separately |
| Good at | Insert or fetch one whole row by key | Scan and aggregate a few columns over many rows |
| Compression | Modest | High (similar values together) |
| Examples | PostgreSQL, MySQL, Oracle | Snowflake, BigQuery, Redshift, Parquet files |
B-trees vs LSM trees
| B-tree | LSM tree | |
|---|---|---|
| How it writes | Updates pages in place | Appends to memory, flushes sorted files, merges them later (compaction) |
| Strength | Fast reads and range scans | Very high write throughput |
| Used by | PostgreSQL, MySQL, Oracle indexes | Cassandra, RocksDB, HBase, ScyllaDB |
Watching the optimiser use an index
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INT, amount REAL)")
con.executemany("INSERT INTO orders (customer_id, amount) VALUES (?, ?)", [(i % 1000, i) for i in range(20000)])
q = "SELECT SUM(amount) FROM orders WHERE customer_id = 42"
print("before:", con.execute("EXPLAIN QUERY PLAN " + q).fetchall()[0][3])
con.execute("CREATE INDEX ix_orders_customer ON orders(customer_id)")
print("after: ", con.execute("EXPLAIN QUERY PLAN " + q).fetchall()[0][3])before: SCAN orders after: SEARCH orders USING INDEX ix_orders_customer (customer_id=?)
"A database has a query processor (parser, cost-based optimiser, executor), a transaction manager (locks or MVCC) and a storage engine (buffer pool, B-tree or LSM structures, write-ahead log). Row stores suit OLTP, column stores suit analytics; B-trees favour reads, LSM trees favour writes. I read EXPLAIN plans to confirm the optimiser uses indexes."
6. ER Modelling
An entity-relationship (ER) model describes the things a business cares about (entities), their properties (attributes) and how they relate (relationships), before any table is created.
| Concept | Meaning | Example (online courses) |
|---|---|---|
| Entity | A thing with independent existence | Student, Course, Instructor |
| Attribute | A property; key, composite, multivalued or derived | email (key), full name (composite), age (derived from birth date) |
| Relationship | An association between entities | Student enrols in Course |
| Cardinality | How many: 1:1, 1:N, M:N | Instructor 1:N Course; Student M:N Course |
| Participation | Mandatory or optional | Every course must have an instructor |
| Weak entity | Identified only through its owner | Lesson numbered within a course |
| Associative entity | Resolves M:N and holds its own attributes | Enrolment (enrolled_on, progress, grade) |
INSTRUCTOR 1 ----< COURSE 1 ----< LESSON (weak: course_id + lesson_no)
1
|
^ (many)
STUDENT 1 ----< ENROLMENT >---- 1 COURSE M:N resolved by ENROLMENT
enrolled_on, progress_pct, grade
From ER model to tables, with keys enforced
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("PRAGMA foreign_keys = ON")
con.executescript("""
CREATE TABLE instructor (instructor_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE course (course_id INTEGER PRIMARY KEY, title TEXT NOT NULL,
instructor_id INT NOT NULL REFERENCES instructor(instructor_id));
CREATE TABLE lesson (course_id INT REFERENCES course(course_id), lesson_no INT, title TEXT,
PRIMARY KEY (course_id, lesson_no)); -- weak entity: composite key
CREATE TABLE student (student_id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL);
CREATE TABLE enrolment (student_id INT REFERENCES student(student_id),
course_id INT REFERENCES course(course_id),
enrolled_on TEXT, progress_pct INT CHECK (progress_pct BETWEEN 0 AND 100),
PRIMARY KEY (student_id, course_id)); -- one enrolment per pair
INSERT INTO instructor VALUES (1, 'Dr Rao');
INSERT INTO course VALUES (10, 'Spark Fundamentals', 1);
INSERT INTO student VALUES (100, 'asha@mail.com');
INSERT INTO enrolment VALUES (100, 10, '2026-03-01', 40);
""")
for bad in ["INSERT INTO course VALUES (11, 'Kafka', 99)",
"INSERT INTO enrolment VALUES (100, 10, '2026-03-02', 10)",
"INSERT INTO enrolment VALUES (100, 10, '2026-03-02', 150)"]:
try:
con.execute(bad)
except sqlite3.IntegrityError as e:
print(f"rejected: {e}")rejected: FOREIGN KEY constraint failed rejected: UNIQUE constraint failed: enrolment.student_id, enrolment.course_id rejected: CHECK constraint failed: progress_pct BETWEEN 0 AND 100
"I start with an ER model: entities, attributes, relationships with cardinality and participation. One-to-many becomes a foreign key on the many side; many-to-many becomes an associative table with a composite key and its own attributes; weak entities get composite keys including the owner. Constraints then enforce the model."
7. Normalisation
Normalisation organises data so each fact is stored once. It removes anomalies: an update anomaly (change a customer's city in many rows, miss one), an insert anomaly (cannot add a product until someone orders it) and a delete anomaly (deleting the last order loses the product's price).
Start from a typical spreadsheet export, where everything sits in one table:
SELECT * FROM order_sheet ORDER BY order_id, product_id;
| order_id | order_date | customer_id | customer_name | customer_city | product_id | product_name | category | unit_price | qty |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 2026-03-01 | 7 | Asha | Pune | 501 | Kettle | Kitchen | 30.00 | 2 |
| 1 | 2026-03-01 | 7 | Asha | Pune | 502 | Toaster | Kitchen | 45.00 | 1 |
| 2 | 2026-03-02 | 8 | Ravi | Delhi | 501 | Kettle | Kitchen | 30.00 | 1 |
| 3 | 2026-03-02 | 7 | Asha | Pune | 503 | Lamp | Home | 20.00 | 3 |
| Normal form | Rule | Problem in the sheet | Fix |
|---|---|---|---|
| 1NF | Atomic values, no repeating groups, a key per row | Satisfied if each row is one order line (no "Kettle, Toaster" lists) | Key = (order_id, product_id) |
| 2NF | 1NF, and no non-key column depends on part of a composite key | order_date, customer depend only on order_id; product_name, price only on product_id | Split out orders and products |
| 3NF | 2NF, and no non-key column depends on another non-key column (no transitive dependency) | customer_name and city depend on customer_id, not the order | Split out customers |
| BCNF | Every determinant is a candidate key | Usually met once 3NF is reached in simple designs | Further split where needed |
The normalised design
CREATE TABLE customers AS SELECT DISTINCT customer_id, customer_name, customer_city FROM order_sheet; CREATE TABLE products AS SELECT DISTINCT product_id, product_name, category, unit_price FROM order_sheet; CREATE TABLE orders AS SELECT DISTINCT order_id, order_date, customer_id FROM order_sheet; CREATE TABLE order_lines AS SELECT order_id, product_id, qty FROM order_sheet; SELECT 'customers' AS tbl, COUNT(*) AS rows FROM customers UNION ALL SELECT 'products', COUNT(*) FROM products UNION ALL SELECT 'orders', COUNT(*) FROM orders UNION ALL SELECT 'order_lines', COUNT(*) FROM order_lines;
| tbl | rows |
|---|---|
| customers | 2 |
| products | 3 |
| orders | 3 |
| order_lines | 4 |
Asha's city is now stored once. Joining the four tables reproduces the original sheet exactly, which proves the decomposition is lossless:
SELECT COUNT(*) AS rows_in_sheet_not_rebuilt FROM (
SELECT * FROM order_sheet
EXCEPT
SELECT ol.order_id, o.order_date, c.customer_id, c.customer_name, c.customer_city,
p.product_id, p.product_name, p.category, p.unit_price, ol.qty
FROM order_lines ol
JOIN orders o USING (order_id)
JOIN customers c USING (customer_id)
JOIN products p USING (product_id));| rows_in_sheet_not_rebuilt |
|---|
| 0 |
One subtle modelling decision: unit_price on products is the current price. Orders must store the price actually charged on the order line, or historical revenue changes when the price list changes. That is "denormalisation for history", and it is correct.
"Normalisation stores each fact once to remove update, insert and delete anomalies. 1NF: atomic values and a key. 2NF: no partial dependency on a composite key. 3NF: no transitive dependency between non-key columns. BCNF: every determinant is a key. I verify a decomposition is lossless by rejoining and comparing."
8. Denormalisation
Denormalisation deliberately stores redundant data to make reads faster or simpler. It is a trade-off, not a mistake: you pay with extra storage and the work of keeping copies consistent.
| Technique | Example | Where |
|---|---|---|
| Copy attributes into another table | customer_city on the order fact | Star-schema dimensions, wide tables |
| Pre-computed aggregates | daily_sales by store | Summary tables, materialized views |
| Snapshot of values at event time | price charged on the order line | OLTP and facts: needed for correctness |
| Nested and repeated fields | order with an array of lines | Document databases, BigQuery, Parquet |
| One big table (OBT) | All columns for one dashboard | BI extracts, ML feature tables |
CREATE TABLE sales_wide AS
SELECT ol.order_id, o.order_date, c.customer_name, c.customer_city,
p.product_name, p.category, ol.qty, p.unit_price, ol.qty * p.unit_price AS line_amount
FROM order_lines ol JOIN orders o USING (order_id)
JOIN customers c USING (customer_id) JOIN products p USING (product_id);
SELECT category, customer_city, SUM(line_amount) AS revenue
FROM sales_wide GROUP BY category, customer_city ORDER BY revenue DESC;| category | customer_city | revenue |
|---|---|---|
| Kitchen | Pune | 105.00 |
| Home | Pune | 60.00 |
| Kitchen | Delhi | 30.00 |
| Normalised (OLTP) | Denormalised (OLAP) | |
|---|---|---|
| Optimised for | Many small writes, integrity | Fast reads and aggregation |
| Joins per query | Many | Few or none |
| Redundancy | Minimal | Deliberate |
| Update cost | One place | Many copies, or rebuild |
"I normalise operational databases for integrity and denormalise analytical models for read speed: star schemas, aggregates, wide tables and nested fields. Some denormalisation is required for correctness, like storing the price charged on each order line. The cost is keeping copies consistent, so denormalised tables should be rebuilt by pipelines, not edited by hand."