This page requires JavaScript to display.
D
Unpacking...
← Advanced Data Engineering
Advanced Data Engineering

Database Systems

How databases work and how to choose one: relational, NoSQL, columnar and graph engines, transactions, storage internals, ER modelling and normal forms.

Contents
1. What a Database Management System Does 2. Types of Databases, with Real Use Cases 3. ACID Properties 4. Isolation Levels and Concurrency 5. Database Architecture: How an Engine Works Inside 6. ER Modelling 7. Normalisation 8. Denormalisation

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:

CapabilityWhat it meansWithout it
Query languageAsk questions declaratively (SQL); the optimiser finds the fast wayHand-written loops over files
Concurrency controlMany users read and write at once without corrupting dataLost updates, half-written records
RecoveryCommitted data survives crashes (write-ahead log)Corrupted files after a power cut
IntegrityTypes, keys, constraints reject bad dataBad data discovered weeks later
SecurityUsers, roles, grants, auditingEveryone sees everything
TermMeaning
SchemaThe structure: tables, columns, types, constraints
Primary keyColumn(s) uniquely identifying a row
Foreign keyColumn referencing another table's key; enforces relationships
IndexA data structure that finds rows without scanning everything
TransactionA unit of work that succeeds or fails as a whole
OLTP / OLAPMany 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.

TypeData modelExamplesReal-world useAvoid when
Relational (RDBMS)Tables, rows, joins, SQL, ACIDPostgreSQL, MySQL, Oracle, SQL ServerBanking transactions, orders, inventory, ERPMassive write scale with flexible schemas
DocumentJSON-like documentsMongoDB, Couchbase, Cosmos DBProduct catalogues with varying attributes, user profiles, contentMany cross-entity joins and transactions
Key-valueKey → valueRedis, DynamoDB, MemcachedSessions, carts, caching, rate limits, feature flagsAd-hoc queries on values
Wide-columnRows with flexible column families, partitioned by keyCassandra, HBase, BigtableTime-ordered events at huge write volume: IoT, messagingJoins, ad-hoc analytics
Columnar (analytical)Columns stored separately, compressedSnowflake, BigQuery, Redshift, ClickHouse, DuckDBDashboards, aggregations over billions of rowsRow-by-row OLTP updates
GraphNodes and edgesNeo4j, Amazon NeptuneFraud rings, recommendations, network and supply-chain analysisSimple tabular reporting
Time-seriesTimestamped measurementsTimescaleDB, InfluxDB, TimestreamMetrics, sensors, market ticks with retention and downsamplingGeneral-purpose relational data
SearchInverted indexesElasticsearch, OpenSearchFull-text product search, log analyticsSystem of record
VectorEmbeddings with similarity searchpgvector, Pinecone, Milvus, WeaviateSemantic search and RAG for LLMsExact-match lookups
NewSQL / distributed SQLSQL and ACID across many nodesCockroachDB, Spanner, YugabyteDBGlobal, strongly consistent OLTPSmall 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;
idnameram_gbsize
1Laptop16NULL
2T-shirtNULLM

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

Say this in the interview

"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

PropertyGuaranteeImplemented by
AtomicityAll statements of a transaction succeed, or none doUndo log / rollback
ConsistencyA transaction moves the database from one valid state to another; constraints always holdConstraints, triggers, application rules
IsolationConcurrent transactions do not see each other's partial workLocks or MVCC snapshots
DurabilityOnce committed, data survives crashesWrite-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 too
Output
transfer 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.

Say this in the interview

"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

AnomalyWhat happens
Dirty readReading another transaction's uncommitted change, which may be rolled back
Non-repeatable readReading the same row twice in one transaction gives different values
Phantom readRe-running a range query returns new rows inserted by others
Lost updateTwo transactions read, modify and write the same row; one overwrite is lost
Write skewTwo transactions read overlapping data and make writes that together break a rule
LevelDirty readNon-repeatablePhantomTypical default
Read uncommittedPossiblePossiblePossibleRarely used
Read committedPreventedPossiblePossiblePostgreSQL, Oracle, SQL Server
Repeatable readPreventedPreventedPossible (prevented in PostgreSQL)MySQL InnoDB
SerializablePreventedPreventedPreventedStrictest; 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")
Output
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.

Say this in the interview

"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)
ComponentRole
Parser and optimiserTurn SQL into a plan; choose join order, join algorithm and index use from statistics
ExecutorRuns the plan: scans, joins (nested loop, hash, merge), sorts, aggregates
Buffer poolKeeps hot pages in memory; most reads never touch disk
WALMakes commits durable cheaply with sequential writes
Lock manager / MVCCProvides isolation between concurrent transactions

Row stores vs column stores

Row store (OLTP)Column store (OLAP)
LayoutAll columns of a row togetherEach column stored separately
Good atInsert or fetch one whole row by keyScan and aggregate a few columns over many rows
CompressionModestHigh (similar values together)
ExamplesPostgreSQL, MySQL, OracleSnowflake, BigQuery, Redshift, Parquet files

B-trees vs LSM trees

B-treeLSM tree
How it writesUpdates pages in placeAppends to memory, flushes sorted files, merges them later (compaction)
StrengthFast reads and range scansVery high write throughput
Used byPostgreSQL, MySQL, Oracle indexesCassandra, 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])
Output
before: SCAN orders
after:  SEARCH orders USING INDEX ix_orders_customer (customer_id=?)
Say this in the interview

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

ConceptMeaningExample (online courses)
EntityA thing with independent existenceStudent, Course, Instructor
AttributeA property; key, composite, multivalued or derivedemail (key), full name (composite), age (derived from birth date)
RelationshipAn association between entitiesStudent enrols in Course
CardinalityHow many: 1:1, 1:N, M:NInstructor 1:N Course; Student M:N Course
ParticipationMandatory or optionalEvery course must have an instructor
Weak entityIdentified only through its ownerLesson numbered within a course
Associative entityResolves M:N and holds its own attributesEnrolment (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}")
Output
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
Say this in the interview

"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_idorder_datecustomer_idcustomer_namecustomer_cityproduct_idproduct_namecategoryunit_priceqty
12026-03-017AshaPune501KettleKitchen30.002
12026-03-017AshaPune502ToasterKitchen45.001
22026-03-028RaviDelhi501KettleKitchen30.001
32026-03-027AshaPune503LampHome20.003
Normal formRuleProblem in the sheetFix
1NFAtomic values, no repeating groups, a key per rowSatisfied if each row is one order line (no "Kettle, Toaster" lists)Key = (order_id, product_id)
2NF1NF, and no non-key column depends on part of a composite keyorder_date, customer depend only on order_id; product_name, price only on product_idSplit out orders and products
3NF2NF, and no non-key column depends on another non-key column (no transitive dependency)customer_name and city depend on customer_id, not the orderSplit out customers
BCNFEvery determinant is a candidate keyUsually met once 3NF is reached in simple designsFurther 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;
tblrows
customers2
products3
orders3
order_lines4

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.

Say this in the interview

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

TechniqueExampleWhere
Copy attributes into another tablecustomer_city on the order factStar-schema dimensions, wide tables
Pre-computed aggregatesdaily_sales by storeSummary tables, materialized views
Snapshot of values at event timeprice charged on the order lineOLTP and facts: needed for correctness
Nested and repeated fieldsorder with an array of linesDocument databases, BigQuery, Parquet
One big table (OBT)All columns for one dashboardBI 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;
categorycustomer_cityrevenue
KitchenPune105.00
HomePune60.00
KitchenDelhi30.00
Normalised (OLTP)Denormalised (OLAP)
Optimised forMany small writes, integrityFast reads and aggregation
Joins per queryManyFew or none
RedundancyMinimalDeliberate
Update costOne placeMany copies, or rebuild
Say this in the interview

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