Skip to content
Visual explainer 4h to learn 4 steps

DBMS: ACID, isolation levels, indexes, normalisation

Explain transactions and indexes with trade-offs.

By Invicly Tech, , in Interview Preparation. About 12 minutes to read.

Topic 21 of 27

In short

DBMS questions cover how databases keep data correct under concurrency and failure, and how they find rows fast. Key topics are ACID, isolation levels, B-tree indexes and normal forms.

Explained simply

A database does two hard jobs at once. It must keep data correct even when many people change it at the same time, and even if the power goes out halfway. And it must find the rows you ask for quickly, even in a table with millions of rows.

A transaction groups several changes into one unit. Moving money from Ana to Bo means two updates. If only the first one happens, money disappears. A transaction promises that both happen or neither does. The four promises are called ACID: atomicity, consistency, isolation and durability.

An index is like the index at the back of a book. Without it, the database reads every row to find what you want. With it, the database jumps almost straight to the right place. But every index must also be updated on every insert, so indexes are not free.

Normalisation is about storing each fact in one place only. If a customer's address is copied into every order, changing it means updating many rows, and you will miss some. Splitting data into related tables removes that risk. Interviewers want you to explain these ideas with small, concrete examples.

Press Play on a diagram to walk through it one step at a time.

MapACID properties
ACID transaction
  • Atomicity
    • All changes or none
  • Consistency
    • Constraints hold before and after
  • Isolation
    • Concurrent transactions do not interfere
  • Durability
    • Committed data survives a crash
CompareIsolation levels
Read committed
  • No dirty reads
  • Non-repeatable reads possible
  • Default in PostgreSQL
Repeatable read
  • Same row reads stay stable
  • Phantoms possible in the SQL standard
  • Default in MySQL InnoDB
Serializable
  • As if run one at a time
  • No anomalies
  • Slowest, may need retries
SequenceA lost update without locking
Transaction A
Database
Transaction B
  1. 1Read stock = 10
    Transaction A to Database: Read stock = 10
  2. 2Read stock = 10
    Transaction B to Database: Read stock = 10
  3. 3Write stock = 9, commit
    Transaction A to Database: Write stock = 9, commit
  4. 4Write stock = 9, commit
    Transaction B to Database: Write stock = 9, commit
  5. 5Two sales, but stock shows 9
    Database to Database: Two sales, but stock shows 9

In depth

How databases actually deliver atomicity and durability

Most databases use a write-ahead log (WAL). Before a change is applied to the data files, a record describing it is appended to the log. On COMMIT, the database forces the log to disk with fsync. Only then does it tell the client the commit succeeded. The data pages themselves can be written later.

If the server crashes, recovery replays the log: committed changes are redone, and changes from transactions that never committed are ignored or undone. That gives durability (committed data survives) and atomicity (half-done transactions vanish). Writing a sequential log is much faster than updating random pages, which is why this design is universal. PostgreSQL calls it WAL; MySQL InnoDB has a redo log and an undo log.

Consistency in ACID means your constraints (primary keys, foreign keys, CHECK rules) hold after every transaction. It is partly the database's job and partly yours.

FlowWhat COMMIT really does
  1. 1
    Change in memory

    Rows updated in the buffer cache

  2. 2
    Append to WAL

    Log record describes the change

  3. 3
    fsync the log

    Log is safely on disk

  4. 4
    Reply COMMIT OK

    Client may now trust the change

  5. 5
    Write pages later

    Checkpoint flushes data files

Isolation levels and the anomalies they allow

The SQL standard defines four levels by which anomalies they prevent. Read uncommitted allows dirty reads (seeing changes that may be rolled back). Read committed blocks dirty reads, but a row read twice may change between reads (non-repeatable read). Repeatable read keeps rows you have read stable, but the standard still allows phantoms: new rows matching your WHERE clause appearing on a second query. Serializable allows no anomalies; the result equals some one-at-a-time order.

Real engines differ from the standard. PostgreSQL treats read uncommitted as read committed, and its repeatable read uses a snapshot, so phantoms do not appear, but write skew still can. Write skew is when two transactions each read the same data, make a decision, and write different rows, breaking a rule together (for example, two doctors both going off call). Only serializable prevents it, and PostgreSQL may abort one transaction with a serialization failure, so your code must retry.

  • Dirty read: blocked from read committed upwards
  • Non-repeatable read: blocked from repeatable read upwards
  • Phantom: blocked by serializable (and by PostgreSQL's snapshot in repeatable read)
  • Lost update: two read-modify-write cycles overwrite each other; use SELECT ... FOR UPDATE or an atomic UPDATE

MVCC: why readers do not block writers

PostgreSQL, MySQL InnoDB and Oracle use MVCC (multi-version concurrency control). Instead of overwriting a row in place, an update creates a new version and keeps the old one for a while. Each transaction reads from a snapshot: it sees the versions that were committed when its snapshot was taken.

The big win is that a long SELECT never blocks an UPDATE, and the UPDATE never blocks the SELECT. Writers still block other writers on the same row, using row locks. In read committed, each statement takes a fresh snapshot. In repeatable read, the whole transaction uses one snapshot.

The cost is old versions piling up. PostgreSQL cleans them with VACUUM (autovacuum runs it automatically). A transaction left open for hours stops cleanup and makes tables bloat, which is a common production problem worth mentioning.

B-tree indexes: how they work and when they do not help

A B-tree index (PostgreSQL and InnoDB actually use the B+ tree variant) keeps keys sorted in pages. Each page holds hundreds of keys, so the tree is very shallow: three or four levels can cover millions of rows. A lookup walks from the root to a leaf, then follows pointers to the table rows. Leaves are linked, so range scans like BETWEEN and ORDER BY are cheap.

A composite index on (country, city) works like a phone book sorted by last name, then first name. It helps WHERE country = 'IN' and WHERE country = 'IN' AND city = 'Pune', but not WHERE city = 'Pune' alone. That is the leftmost-prefix rule.

Indexes may be ignored when the query returns a large share of the table, when you wrap the column in a function (WHERE lower(email) = ... needs an expression index), or on tiny tables. Every index slows inserts and updates and uses disk, so add them for real queries, and check with EXPLAIN.

  • Lookup cost is O(log n), and the base is large, so few page reads
  • Covering index: all needed columns are in the index, no table visit
  • Hash index: equality only, no ranges or sorting
  • Clustered (InnoDB primary key) stores rows in index order

Normal forms, with one table taken apart

Take orders(order_id, customer_name, customer_city, product_ids, product_names). First normal form (1NF): each cell holds one value, so a list like product_ids must become separate rows in an order_items table. Second normal form (2NF): in a table with a composite key, every non-key column must depend on the whole key. In order_items(order_id, product_id, product_name), the name depends only on product_id, so it moves to a products table. Third normal form (3NF): non-key columns must not depend on other non-key columns. customer_city depends on the customer, not on the order, so it moves to a customers table.

The short rule: every non-key column depends on the key, the whole key, and nothing but the key. BCNF is a slightly stricter 3NF. In practice, reporting and read-heavy systems denormalise on purpose, for example storing an order total, and accept the cost of keeping it in sync.

MapOne messy orders table, normalised
orders (messy)
  • customers
    • customer_id (PK)
    • name, city
  • orders
    • order_id (PK)
    • customer_id (FK)
    • ordered_at
  • order_items
    • order_id + product_id (PK)
    • quantity
  • products
    • product_id (PK)
    • name, price

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Explain ACID properties with examples~1h
  2. 2
    Compare isolation levels and anomalies~1h
  3. 3
    Explain B-tree indexes and their trade-offs~1h
  4. 4
    Walk through normal forms~1h

Key points

  • Higher isolation prevents more anomalies but reduces concurrency.
  • B-tree indexes give O(log n) lookups and support range queries and sorting.
  • Indexes speed reads but slow writes and use extra storage.
  • Normalise to remove redundancy; denormalise deliberately for read performance.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;  -- or ROLLBACK on error: both happen or neither

CREATE INDEX idx_accounts_owner ON accounts (owner_id);
EXPLAIN SELECT * FROM accounts WHERE owner_id = 7;

Fixing the lost update on stock

Two customers buy the last items at the same moment and stock goes wrong. Step 1: explain that read committed allows this, because both transactions read 10 before either writes. Step 2: offer fix one, an atomic update that lets the database do the read and the write together, with a condition so stock never goes negative. Step 3: offer fix two, lock the row with SELECT ... FOR UPDATE when the logic needs to read first. Step 4: mention that serializable isolation also prevents it but needs retry logic.

sql
-- Fix 1: atomic update, check the row count in your app
UPDATE products SET stock = stock - 1
WHERE id = 42 AND stock > 0;

-- Fix 2: lock the row, then decide
BEGIN;
SELECT stock FROM products WHERE id = 42 FOR UPDATE;
-- app checks stock > 0 here
UPDATE products SET stock = stock - 1 WHERE id = 42;
COMMIT;

Why is my index not used?

The interviewer shows a slow query on users with an index on email. Step 1: run EXPLAIN and see a Seq Scan. Step 2: notice the query uses lower(email), so the plain index cannot match. Step 3: create an expression index on lower(email). Step 4: run EXPLAIN again and see an Index Scan. Also mention the other common causes: low selectivity, a type mismatch, and stale statistics that ANALYZE fixes.

sql
EXPLAIN SELECT id FROM users WHERE lower(email) = 'ana@example.com';
-- Seq Scan on users ...

CREATE INDEX idx_users_email_lower ON users (lower(email));
ANALYZE users;

EXPLAIN SELECT id FROM users WHERE lower(email) = 'ana@example.com';
-- Index Scan using idx_users_email_lower on users ...

Quick reference

  • WAL: log the change, fsync on COMMIT, write data pages later; replay on crash
  • Read committed: no dirty reads; repeatable read: stable rows; serializable: no anomalies
  • Defaults: PostgreSQL read committed, MySQL InnoDB repeatable read
  • Write skew is only prevented by serializable; be ready to retry serialization failures
  • MVCC: readers do not block writers; old row versions are cleaned by VACUUM
  • Composite index (a, b) helps WHERE a and WHERE a AND b, not WHERE b alone
  • 3NF: every non-key column depends on the key, the whole key, and nothing but the key
  • EXPLAIN ANALYZE runs the query and shows the real plan, rows and timing

Common mistakes

  • Listing ACID without a concrete example such as a bank transfer.
  • Claiming indexes are always good.
  • Mixing up non-repeatable reads and phantom reads.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which component lets a database survive a crash right after COMMIT returns?

Question 2

2A table has an index on (last_name, first_name). Which query can use it best?

Question 3

3Two transactions each check that at least one doctor is on call, then each takes a different doctor off call. Which anomaly is this?

Question 4

4In MVCC databases like PostgreSQL, what is true?

Question 5

5order_items(order_id, product_id, product_name) has primary key (order_id, product_id). Which normal form does it break?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Give a one-sentence real example for each ACID letter, using an online shop.

  2. Exercise 2medium

    In two psql sessions, show a non-repeatable read under read committed, then show it disappears under repeatable read.

  3. Exercise 3hard

    Normalise this table to 3NF: enrolments(student_id, student_name, course_id, course_title, teacher_name, teacher_office, grade), key (student_id, course_id). Assume one teacher per course.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the default isolation level in PostgreSQL and MySQL?
PostgreSQL defaults to read committed. MySQL with InnoDB defaults to repeatable read.
Should I index every column I filter on?
No. Each index slows writes and uses space, and the planner skips indexes that do not narrow results much. Index the columns your frequent, slow queries filter, join or sort on, and confirm with EXPLAIN.
What is the difference between a phantom read and a non-repeatable read?
A non-repeatable read is the same row returning a different value. A phantom is a re-run query returning a different set of rows, because rows were inserted or deleted.
Is denormalisation bad?
Not when done on purpose. It speeds up reads at the cost of extra storage and the work of keeping copies in sync, which is often a fair trade for dashboards and read-heavy APIs.
ShareXLinkedInWhatsApp