DBMS interview questions: transactions, normalization, indexing and recovery
DBMS interview questions test the theory underneath every relational database: ACID transactions, keys and normalization from 1NF to BCNF, B+ tree indexes, isolation levels and the anomalies they allow, concurrency control with locking or MVCC, and crash recovery through write-ahead logging. They appear in campus placements as a core CS subject and in backend interviews as "why is this query slow" or "why did this balance go wrong" questions. Explain each concept with a small table or schedule, not just a definition.
By Evin JohnPublished 10 min read
What DBMS rounds cover
In campus and fresher interviews, DBMS is one of the standard CS fundamentals subjects, and questions follow the textbook order: data models, keys, normalization, transactions, concurrency and recovery, with short exercises such as finding candidate keys from functional dependencies. In backend and data interviews the same theory comes back as practical questions: which index would you add, why did two users book the same seat, what happens to a committed order if the server crashes a millisecond later. This page stays on theory and internals. Query writing practice (joins, grouping, window functions) is a separate skill you should prepare on its own.
Fundamentals: DBMS, models and keys
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does a DBMS give you that files do not? | Motivation | Concurrent access without corruption, transactions, recovery after crashes, a query language, integrity constraints, access control and data independence from the physical layout. |
| DBMS versus RDBMS? | Vocabulary | An RDBMS is a DBMS built on the relational model: data in tables (relations) with keys and constraints, queried with relational operations, usually through SQL. |
| What are the three levels of schema? | Architecture | External (views for users), conceptual (the logical schema of all tables) and internal (storage and indexes). Logical and physical data independence mean each level can change without breaking the one above. |
| Super key, candidate key, primary key? | Keys | A super key is any set of attributes that identifies a row uniquely. A candidate key is a minimal super key. The primary key is the candidate key you choose; the others become alternate keys. |
| What is a foreign key and what does it enforce? | Integrity | A column that must match a key in another table (or be null). It enforces referential integrity, with rules such as restrict or cascade on delete. |
| Natural key versus surrogate key? | Design judgment | A natural key comes from the data (an email, a tax id) and can change or be reused. A surrogate key is generated and meaningless, which keeps joins stable; keep a unique constraint on the natural key too. |
| What is a composite key? | Keys | A key of two or more columns, common in link tables such as enrollment(student_id, course_id). |
| Explain entities, attributes and relationships in an ER diagram. | Modeling | Entities become tables, attributes become columns, and relationships become foreign keys (one-to-many) or link tables (many-to-many). Weak entities borrow part of their key from an owner. |
| What are the basic relational algebra operations? | Theory | Selection, projection, union, set difference, Cartesian product and rename, with join, intersection and division derived from them. SQL queries are translated into trees of these operations. |
| What is a view, and is it stored? | Abstraction | A named query. A normal view is computed when used; a materialized view stores its result and must be refreshed. |
Functional dependencies and normalization
Normalization questions start with a badly designed table and ask what goes wrong. Take orders(order_id, product_id, quantity, product_name, customer_id, customer_city). The key is (order_id, product_id). The product name depends only on product_id, and customer_id depends only on order_id; both depend on part of the key, so the table is not in 2NF, and renaming a product means updating many rows. Fixing 2NF splits it into order_lines(order_id, product_id, quantity), products(product_id, product_name) and orders(order_id, customer_id, customer_city). Now orders has a transitive dependency: order_id determines customer_id, which determines customer_city, so orders is not in 3NF until the city moves to a customers table. Those are update, insert and delete anomalies, and removing them is the whole point.
| Normal form | Rule | Anomaly it removes |
|---|---|---|
| 1NF | Every column holds one atomic value; no repeating groups. | Lists inside a cell that cannot be queried or constrained. |
| 2NF | 1NF, and no non-key attribute depends on only part of a composite key. | Repeating product data on every order line. |
| 3NF | 2NF, and no non-key attribute depends on another non-key attribute. | Customer city repeated on every order and drifting out of sync. |
| BCNF | For every non-trivial dependency X to Y, X is a super key. | Rare cases 3NF allows, where a non-key attribute determines part of a key. |
| 4NF | BCNF, and no multivalued dependencies other than on a key. | Independent lists (a teacher's subjects and languages) multiplied together. |
- What is a functional dependency? X determines Y if any two rows that agree on X must agree on Y. Dependencies come from the meaning of the data, not from the rows you happen to see.
- How do you find candidate keys from a set of dependencies? Compute attribute closures. Any attribute that never appears on the right side must be in every key; start from those and add attributes until the closure covers everything.
- What is a lossless join decomposition? Splitting a table so that joining the parts gives back exactly the original rows. A split is lossless if the shared attributes form a key of at least one part.
- Is every 3NF table in BCNF? No. A table can be in 3NF but not BCNF when a non-key attribute determines part of a candidate key. BCNF decomposition may lose dependency preservation, which is why 3NF is sometimes kept on purpose.
- When would you denormalize? When reads dominate and joins are measurably too slow: reporting tables, cached counts, read models. Accept the cost of keeping copies in sync and say how you would do it.
from itertools import combinations
ATTRS = "ABCDE"
FDS = [("A", "B"), ("B", "C"), ("CD", "E")]
def closure(attrs):
result = set(attrs)
changed = True
while changed:
changed = False
for left, right in FDS:
if set(left) <= result and not set(right) <= result:
result |= set(right)
changed = True
return result
def candidate_keys():
keys = []
for size in range(1, len(ATTRS) + 1):
for combo in combinations(ATTRS, size):
if closure(combo) == set(ATTRS) and not any(set(k) <= set(combo) for k in keys):
keys.append("".join(combo))
return keys
print(sorted(closure("A"))) # ['A', 'B', 'C']
print(candidate_keys()) # ['AD']Indexing and B+ trees
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Why do databases use B+ trees rather than binary trees? | Storage awareness | Each node is a disk or memory page holding hundreds of keys, so the tree is only a few levels deep and a lookup reads few pages. Binary trees would be tall and touch many pages. |
| B tree versus B+ tree? | Structure | In a B+ tree all data pointers live in the leaves and the leaves are linked in order, so range scans walk the leaf chain. Internal nodes hold only keys, which fit more per page. |
| Clustered versus non-clustered index? | Physical layout | A clustered index stores the table rows in key order, so there can be only one. A non-clustered (secondary) index stores keys plus a pointer or the primary key, which can mean an extra lookup per row. |
| What is a covering index? | Optimization | An index that holds every column a query needs, so the engine answers from the index without touching the table. |
| How does a composite index on (a, b) get used? | Column order | It serves filters on a, or on a and b, and sorting by a then b. A filter on b alone usually cannot use it efficiently: the leftmost prefix rule. |
| When does an index hurt? | Trade-offs | Every insert, update and delete must maintain it, it takes space, and for low-selectivity filters a full scan is cheaper than many random reads. |
| Hash index versus B+ tree index? | Choice | A hash index answers equality lookups in about O(1) but cannot do ranges or ordering. B+ trees do both in O(log n). |
| Why might the database ignore your index? | Optimizer | The optimizer estimates it would read most of the table, statistics are stale, or the query wraps the column in a function or casts it, so the index order no longer applies. |
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INT, created_at TEXT, total INT)")
db.execute("CREATE INDEX idx_customer_date ON orders (customer_id, created_at)")
def plan(sql):
return [row[-1] for row in db.execute("EXPLAIN QUERY PLAN " + sql)]
print(plan("SELECT * FROM orders WHERE customer_id = 7 AND created_at > '2026-01-01'"))
print(plan("SELECT * FROM orders WHERE created_at > '2026-01-01'"))
# ['SEARCH orders USING INDEX idx_customer_date (customer_id=? AND created_at>?)']
# ['SCAN orders']Transactions, ACID and isolation levels
- Explain ACID with one example. A transfer of 100 between two accounts. Atomicity: both updates happen or neither. Consistency: constraints such as "balance not negative" still hold. Isolation: another transaction never sees money missing from both accounts. Durability: once committed, the transfer survives a crash.
- What is a schedule, and what makes it serializable? An interleaving of operations from several transactions. It is serializable if its effect equals some serial order. Conflict serializability is tested by building a precedence graph and checking it for cycles.
- What are the read anomalies? A dirty read sees uncommitted data. A non-repeatable read gets a different value when it reads the same row twice. A phantom read sees new rows appear in a repeated range query.
- What are lost update and write skew? A lost update is two transactions reading a value and both writing a change based on it, so one change vanishes. Write skew is two transactions reading the same rows, each updating a different row, and together breaking a rule neither broke alone (two doctors both going off call).
- What do the four standard isolation levels prevent? Read uncommitted prevents almost nothing. Read committed prevents dirty reads. Repeatable read also prevents non-repeatable reads. Serializable prevents all anomalies. Real engines differ in the details.
- What are the default levels in common databases? PostgreSQL, SQL Server and Oracle default to read committed; MySQL with InnoDB defaults to repeatable read. Check the version you use, since behavior at each level is engine specific.
- How do you prevent a lost update in practice? An atomic update (
SET balance = balance - 100), a row lock withSELECT ... FOR UPDATE, optimistic concurrency with a version column, or a stricter isolation level that detects the conflict.
| Level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| Read uncommitted | Possible | Possible | Possible |
| Read committed | Prevented | Possible | Possible |
| Repeatable read | Prevented | Prevented | Possible |
| Serializable | Prevented | Prevented | Prevented |
Concurrency control inside the database
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is two-phase locking? | Protocols | A transaction acquires locks in a growing phase and releases them in a shrinking phase, never acquiring after releasing. That guarantees conflict serializability. Strict 2PL holds write locks until commit, which also prevents cascading aborts. |
| Shared versus exclusive locks? | Lock modes | Many transactions can hold shared (read) locks on an item; an exclusive (write) lock excludes everyone else. Intention locks on tables let the engine check row locks quickly before locking a whole table. |
| Row-level versus table-level locking? | Granularity | Row locks allow more concurrency but cost more to manage. Engines may escalate many row locks to a table lock to save memory. |
| What is MVCC? | Modern engines | Multi-version concurrency control keeps old row versions so readers see a consistent snapshot without blocking writers. Writers still conflict with each other. Old versions must be cleaned up later (vacuum or purge). |
| Optimistic versus pessimistic concurrency control? | Strategy | Pessimistic locks before acting and suits high contention. Optimistic works without locks and validates at commit (or with a version column), retrying on conflict; it suits low contention. |
| How does a database handle deadlocks between transactions? | Deadlock in DBs | It builds a wait-for graph of transactions, detects a cycle, picks a victim (often the one with the least work done) and rolls it back with an error. Applications must catch that error and retry the transaction. |
| What is timestamp ordering? | Alternative protocol | Each transaction gets a timestamp, and conflicting operations must run in timestamp order; a transaction that would break the order is aborted and restarted. |
Recovery and durability
- What is write-ahead logging? Before a changed data page is written to disk, the log record describing the change must be on stable storage. A commit is durable once its commit record is flushed, even if the data pages are still only in memory.
- What are redo and undo? After a crash, redo replays logged changes of committed transactions that may not have reached the data files; undo rolls back changes of transactions that never committed.
- What is a checkpoint? A point where the engine records which pages are dirty and flushes work, so recovery can start reading the log from there instead of from the beginning.
- What are steal and no-force? Steal lets the buffer manager write uncommitted pages to disk (so undo is needed); no-force means commits do not wait for data pages to be written (so redo is needed). Most engines use steal and no-force for speed, which is why they need both.
- What is ARIES in one sentence? A classic recovery algorithm with three passes after a crash: analysis to find what was in flight, redo to repeat history, and undo to roll back losers.
- What is the difference between a backup and replication? Replication copies changes to another server continuously and also copies mistakes such as a dropped table. Backups plus logs allow point-in-time recovery to before the mistake.
Joins and query processing
- What join types exist? Inner, left, right and full outer joins, cross join, and self join. Semi-joins (
EXISTS) and anti-joins (NOT EXISTS) are how the optimizer thinks about many subqueries. - What algorithms does the engine use for joins? Nested loop (good when one side is small and the other is indexed), hash join (build a hash table on the smaller input, probe with the larger; equality only), and sort-merge join (both inputs sorted on the join key, good for large sorted inputs and ranges).
- What does the query optimizer do? It rewrites the query, estimates the cost of alternative plans from table statistics, and picks join order, join algorithms and access paths. Bad estimates are the usual cause of a bad plan.
- What is the N+1 query problem? Fetching a list with one query and then each item's details with one query per item. A join or one batched
INquery fixes it.
Senior and scenario questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| A query that took 20 ms now takes 20 seconds, with no code change. Where do you start? | Diagnosis | Compare the current execution plan with the old one. Stale statistics, data growth past a threshold or a changed parameter often flip the optimizer to a scan or a different join order. |
| A table has twelve indexes and inserts are slow. What do you do? | Index cost | Find unused and duplicate indexes from usage statistics, remove them, and keep the ones that serve real queries, possibly as fewer composite or covering indexes. |
| Your service logs deadlock errors from the database a few times a day. How do you handle them? | Deadlocks in practice | Retry the victim transaction, then reduce the cause: touch rows in a consistent order, keep transactions short, and index the columns used in locking reads so fewer rows are locked. |
| Reports run on the primary database slow down checkout. What would you change? | Workload isolation | Move reporting to a read replica or a separate analytics store, accepting replication lag, and keep long-running reads away from the write path. |
| How would you add a column with a default to a very large table without downtime? | Schema changes | Check whether your engine adds it as a metadata-only change; if not, add it nullable, backfill in batches, then add the default and constraint. |
| When would you choose a document or key-value store instead? | Model choice | When access is by key, the schema varies a lot or scale-out writes matter more than joins and multi-row transactions. See the trade-offs in the system design guides. |
Fictional example
- Interviewer
- Our booking code reads the seat's status, and if it is free it inserts a booking. Twice this month two people got the same seat. What happened, and how would you fix it?
- Candidate
- That is a check-then-act race between two transactions. Both read the seat as free before either inserted, and at read committed nothing stops that, because neither read sees the other's uncommitted insert. I would fix it in the database rather than the application. The simplest fix is a unique constraint on (show_id, seat_id) in the bookings table: the second insert fails and we tell the user the seat is gone. If the flow needs a hold first, I would lock the seat row with SELECT ... FOR UPDATE inside the transaction, so the second transaction waits and then sees it as taken. Serializable isolation would also catch it, but then every conflicting transaction can fail with a serialization error and the code needs a retry loop. I prefer the constraint because it holds even if someone writes a new code path later.
How to prepare for DBMS interview questions
- Work the normalization exercisesGiven dependencies, find closures and candidate keys, name the highest normal form and decompose. Do ten by hand; they come up often in campus rounds.
- Draw the schedulesFor each anomaly (dirty read, lost update, write skew, phantom), write a two-transaction timeline. Being able to draw one on request is the clearest proof you understand isolation.
- Explain one engine's internalsPick the database you know best and learn its default isolation level, how it implements MVCC or locking, and what its write-ahead log is called.
- Read a few query plansCreate a table, add indexes and run EXPLAIN on queries that use and ignore them. Plans turn index theory into something you can describe from experience.
- Keep the vocabulary tightCandidate key, functional dependency, lossless join, serializability, 2PL, MVCC, WAL, checkpoint. Interviewers notice when a term is used loosely.
DBMS theory has close neighbors. The operating system interview questions page covers paging, the page cache and fsync underneath the storage engine, and multithreading interview questions covers the same races at the application level. For architecture-level questions, see SQL versus NoSQL, sharding and the data engineer interview questions page.
Normalization and isolation answers improve fastest when you say them aloud and then check them. Natively, an AI interview assistant for Mac and Windows, transcribes a mock DBMS round, can suggest an answer when a schedule question stalls you, and reads a dependency exercise or schema from a screenshot to check your decomposition. With Pro or the free trial, its suggestions can also use your résumé and the job description you add, and the transcript and notes are kept for later review.
Questions people ask
What are the most important DBMS interview topics?
ACID transactions, keys, normalization up to BCNF, indexing with B+ trees, isolation levels and their anomalies, concurrency control with locking or MVCC, and crash recovery with write-ahead logging.
What is the difference between 3NF and BCNF?
3NF allows a dependency X to A when A is part of a candidate key. BCNF does not: for every non-trivial dependency, X must be a super key. Most 3NF tables are also in BCNF.
What is the difference between a clustered and a non-clustered index?
A clustered index stores the table rows themselves in key order, so a table has at most one. A non-clustered index stores keys with pointers to the rows, and a table can have many.
How do I prepare for DBMS questions for freshers?
Practice finding candidate keys and normal forms from functional dependencies, draw two-transaction schedules for each anomaly, and learn how one real database implements isolation and recovery.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
