Top 50 DBMS Interview Questions (2026)

The 50 DBMS questions interviewers actually ask, with direct answers, real SQL, comparison tables, and what the interviewer is listening for. Grouped for freshers, intermediate, and experienced rounds.

50 questions with answers

What Is DBMS?

Key Takeaways

  • A DBMS is software that stores, retrieves, and manages data while enforcing rules like consistency, concurrency control, and access permissions. The database is the data; the DBMS is the engine around it.
  • Interviews test the model behind the tool: relational structure, ACID transactions, normalization, indexing, and how joins and queries actually run.
  • Judgment counts as much as recall: when to normalize versus denormalize, when an index helps versus hurts, and when a relational store fits versus a NoSQL one.
  • This page is a question bank: work your tier first, read one tier up, and say answers out loud because reasoning and delivery get evaluated too.

A database management system (DBMS) is the software layer that sits between your application and stored data. It handles the mechanics you'd otherwise write by hand: defining structure, reading and writing records, running transactions so concurrent users don't corrupt each other's work, enforcing constraints, and controlling who can access what. The database is the collection of data; the DBMS is the engine that governs it. A relational DBMS (RDBMS) organizes data into tables of rows and columns with defined relationships, and you query it with SQL. The PostgreSQL documentation describes SQL as the language for defining that structure and asking questions of the data, and it's the reference this bank leans on for relational concepts. In interviews, DBMS questions probe how you reason about the model underneath the syntax: what ACID guarantees mean, why normalization reduces redundancy, when an index speeds a query versus slows a write, and how a join executes. This page collects the 50 questions that come up most, each with a direct answer plus real SQL where a candidate would actually write it. Pair this bank with our AI interview preparation guides for the live-interview format, since the first DBMS round is increasingly an AI-driven technical screen.

50Questions with answers on this page
3Difficulty tiers: freshers, intermediate, experienced
10Quiz questions to test yourself
30-45 minTypical length of a DBMS technical round

Watch: Introduction to Database Management Systems

Video: Introduction to Database Management Systems (Neso Academy, YouTube)

Test yourself and earn a certificate

10 quick questions. Score 70%+ to download your DBMS certificate.

Jump to quiz

All Questions on This Page

50 questions
DBMS Interview Questions for Freshers
  1. 1. What is a DBMS and why is it used?
  2. 2. What is the difference between a DBMS and an RDBMS?
  3. 3. What is SQL and what are its main sub-languages?
  4. 4. What is a primary key, and what rules must it follow?
  5. 5. What is the difference between a primary key and a unique key?
  6. 6. What is a foreign key and what does it enforce?
  7. 7. What are candidate keys and super keys?
  8. 8. What are the ACID properties of a transaction?
  9. 9. What is a transaction, and what are COMMIT and ROLLBACK?
  10. 10. What is normalization and why do it?
  11. 11. What are 1NF, 2NF, and 3NF?
  12. 12. What is denormalization and when is it used?
  13. 13. What is the difference between SQL and NoSQL databases?
  14. 14. How does a basic SELECT query work?
  15. 15. What is the difference between WHERE and HAVING?
  16. 16. What does DISTINCT do, and how is it different from GROUP BY?
  17. 17. How does NULL behave in SQL?
  18. 18. What are constraints, and what types are there?
  19. 19. Classify these commands: CREATE, INSERT, GRANT, COMMIT, TRUNCATE.
DBMS Intermediate Interview Questions
  1. 20. What are the types of SQL joins?
  2. 21. What is the difference between an inner join and an outer join, with an example?
  3. 22. What is an index and how does it speed up queries?
  4. 23. What is the difference between a clustered and a non-clustered index?
  5. 24. When can an index hurt performance?
  6. 25. What is a composite index and why does column order matter?
  7. 26. What are the SQL transaction isolation levels?
  8. 27. What are dirty reads, non-repeatable reads, and phantom reads?
  9. 28. What is a deadlock and how do databases handle it?
  10. 29. What is the difference between optimistic and pessimistic locking?
  11. 30. What is a stored procedure, and when would you use one?
  12. 31. What is a view, and what is a materialized view?
  13. 32. How do aggregate functions work with GROUP BY?
  14. 33. What is a subquery, and when would you use one over a join?
  15. 34. What is the difference between ACID and BASE?
  16. 35. What is the CAP theorem?
  17. 36. What does a query optimizer do, and what is an execution plan?
DBMS Interview Questions for Experienced Engineers
  1. 37. How does a B-tree index actually find a row?
  2. 38. What is the difference between partitioning and sharding?
  3. 39. How does database replication work, and what are the trade-offs?
  4. 40. What is MVCC and why do databases use it?
  5. 41. What is the N+1 query problem and how do you fix it?
  6. 42. Why do applications use a database connection pool?
  7. 43. When would you choose NoSQL over a relational database?
  8. 44. How do you decide when to denormalize a schema in production?
  9. 45. Walk me through diagnosing a slow query in production.
  10. 46. How do you maintain consistency across services in a distributed system?
  11. 47. What kinds of locks do databases use, and how do they affect concurrency?
  12. 48. What is a write-ahead log and why does it matter for durability?
  13. 49. How do you run a schema migration on a large table without downtime?
  14. 50. Design question: model the schema for an e-commerce orders system.

DBMS Interview Questions for Freshers

Freshers19 questions

The fundamentals every entry-level round checks: what a DBMS is, keys, ACID, normalization basics, and the SQL underneath. If any answer here surprises you, that's your study list.

Q1. What is a DBMS and why is it used?

A DBMS is software that stores, retrieves, and manages data while handling the hard parts for you: structure, concurrent access, transactions, constraints, and permissions. The database is the data itself; the DBMS is the engine that governs how it's stored and used.

Teams use it instead of flat files because it gives shared multi-user access without corruption, enforces data integrity through constraints, controls who can read or write, and recovers cleanly after a crash. Doing all that by hand in files is error-prone and doesn't scale.

Key point: Interviewers open with this to hear whether you separate 'the data' from 'the software managing it'. The concurrency, integrity, and recovery as the reasons a DBMS exists.

Q2. What is the difference between a DBMS and an RDBMS?

A DBMS is any system that manages data; an RDBMS is a DBMS that organizes data into tables of rows and columns with defined relationships, and enforces rules through keys and constraints. Every RDBMS is a DBMS, but not every DBMS is relational.

In practice, RDBMS means SQL databases like PostgreSQL, MySQL, and Oracle: structured tables, foreign keys, and ACID transactions. A plain DBMS could be a simpler file-based or hierarchical store without the relational model. Most interview questions assume an RDBMS unless they say otherwise.

DBMSRDBMS
Data modelAny (files, hierarchical, etc.)Tables with rows and columns
RelationshipsNot enforced by the modelForeign keys enforce them
ExampleFile-based storesPostgreSQL, MySQL, Oracle

Key point: The one-line answer is 'an RDBMS is a DBMS built on the relational table model with keys and constraints'. Interviewers check you know RDBMS is a subset.

Q3. What is SQL and what are its main sub-languages?

SQL (Structured Query Language) is the standard language for defining, querying, and modifying data in a relational database. You use it to create and change tables, insert and update rows, control who has access, manage transactions, and ask questions of the data with SELECT. It's declarative: you say what you want, and the engine works out how.

It splits into sub-languages by purpose: DDL defines structure (CREATE, ALTER, DROP), DML changes data (INSERT, UPDATE, DELETE), DQL queries it (SELECT), DCL controls access (GRANT, REVOKE), and TCL manages transactions (COMMIT, ROLLBACK). Knowing which command belongs to which group is a common quick check.

Sub-languagePurposeExample commands
DDLDefine structureCREATE, ALTER, DROP
DMLChange dataINSERT, UPDATE, DELETE
DQLQuery dataSELECT
DCLControl accessGRANT, REVOKE
TCLManage transactionsCOMMIT, ROLLBACK, SAVEPOINT

Key point: If asked to classify a command, the trap is TRUNCATE. It's DDL, not DML, because it operates on the table structure, not row by row.

Q4. What is a primary key, and what rules must it follow?

A primary key is the column or set of columns that uniquely identifies each row in a table. No two rows can share the same primary key value, and it can never be NULL, so every row is guaranteed addressable.

A table has at most one primary key, though it can span multiple columns (a composite key). Most databases automatically create a unique index on it, which is why lookups by primary key are fast. If several columns could serve as the key, those are candidate keys, and you pick one as primary.

sql
CREATE TABLE employees (
  id         BIGINT PRIMARY KEY,
  email      TEXT NOT NULL UNIQUE,
  full_name  TEXT NOT NULL
);

Key point: State both rules in practice: unique and never NULL. Forgetting the NULL rule is the most common slip on this one.

Q5. What is the difference between a primary key and a unique key?

Both enforce uniqueness, so no duplicate values are allowed. The differences: a table can have only one primary key but many unique keys, and a primary key can't be NULL while a unique key usually allows one NULL (behavior varies slightly by database).

Use the primary key as the row's main identifier, and unique keys for other columns that must stay unique, like an email or a username. A foreign key from another table typically references the primary key, not a unique key.

Key point: The two distinctions to name are 'one per table vs many' and 'NULL not allowed vs one NULL allowed'. Saying only 'both are unique' misses the point.

Q6. What is a foreign key and what does it enforce?

A foreign key is a column in one table that references the primary key of another table, linking the two. It enforces referential integrity: you can't insert a row whose foreign key value doesn't exist in the referenced table, and you can't delete a referenced row while children still point to it (unless you set a cascade rule).

This is how a relational database keeps relationships honest. An orders table with a customer_id foreign key can't have an order pointing at a customer who was never created, which is exactly the kind of orphaned-data bug foreign keys prevent.

sql
CREATE TABLE orders (
  id          BIGINT PRIMARY KEY,
  customer_id BIGINT NOT NULL REFERENCES customers(id),
  total_cents INT NOT NULL
);

Key point: Say 'referential integrity' explicitly, then give the orphaned-order example. the question needs the term plus a concrete case.

Q7. What are candidate keys and super keys?

A super key is any set of columns that uniquely identifies a row, including sets with extra unnecessary columns. A candidate key is a minimal super key: it uniquely identifies rows and has no redundant column you could remove and still stay unique.

From the candidate keys you choose one as the primary key; the rest are called alternate keys. So the hierarchy is: super keys contain candidate keys, one candidate key becomes the primary key. For example, both employee_id and email might be candidate keys; you pick one as primary.

Key point: The distinction the key signal is is 'minimal'. A candidate key is a super key with nothing to spare; that word is the whole answer.

Q8. What are the ACID properties of a transaction?

ACID is the set of guarantees a transaction gives so data stays correct. Atomicity means all steps happen or none do; a half-done transfer never survives. Consistency means a transaction moves the database from one valid state to another, respecting all constraints.

Isolation means concurrent transactions don't see each other's uncommitted work, so they behave as if run one at a time. Durability means once a transaction commits, its result survives a crash or power loss. Together they're why you trust a database with money.

  • Atomicity: all-or-nothing; a failure rolls the whole transaction back.
  • Consistency: constraints and rules hold before and after.
  • Isolation: concurrent transactions don't corrupt each other.
  • Durability: committed data survives crashes.

Key point: Give a one-line real example for atomicity (a bank transfer). Reciting the four words without an example reads memorized.

Watch a deeper explanation

Video: Relational Database ACID Transactions (Explained by Example) (Hussein Nasser, YouTube)

Q9. What is a transaction, and what are COMMIT and ROLLBACK?

A transaction is a unit of work made of one or more SQL statements that must succeed or fail together. You start it, run the statements, and then either COMMIT to make every change permanent, or ROLLBACK to undo all of them as if nothing happened.

The classic case is a bank transfer: debit one account and credit another. If the credit fails after the debit, you ROLLBACK so money isn't lost. COMMIT is what makes changes durable and visible to other transactions; before it, the work is provisional.

sql
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;   -- or ROLLBACK to undo both

Key point: COMMIT maps to durability and ROLLBACK to atomicity. Connecting the commands back to ACID shows you understand the mechanism, not just the keywords.

Q10. What is normalization and why do it?

Normalization is organizing columns and tables to reduce redundant data. Instead of repeating a customer's address in every order row, you store it once in a customers table and reference it. The goal is to remove duplication so the same fact lives in exactly one place.

The payoff is fewer anomalies. When data is duplicated, an update has to change every copy or the data goes inconsistent, a delete can wipe out information you still needed, and inserts get awkward. Normalization removes those update, delete, and insert anomalies by design.

Key point: The three anomalies (update, delete, insert) as the reason. Saying 'to save space' undersells it; the real win is consistency.

Watch a deeper explanation

Video: Database Design Course - Learn how to design and plan a database for beginners (freeCodeCamp.org, YouTube)

Q11. What are 1NF, 2NF, and 3NF?

First normal form (1NF) requires each column to hold a single atomic value, no lists or repeating groups in a cell, and each row to be unique. Second normal form (2NF) is 1NF plus every non-key column depending on the whole primary key, not just part of a composite key.

Third normal form (3NF) is 2NF plus no transitive dependencies: non-key columns must depend only on the key, not on another non-key column. Most schemas aim for 3NF as the practical sweet spot between clean structure and query simplicity.

FormRule addedRemoves
1NFAtomic values, no repeating groupsMulti-valued cells
2NFNo partial dependency on a composite keyRedundancy from partial keys
3NFNo transitive dependencyNon-key depends on non-key

Key point: Remember the ladder: 1NF atomic, 2NF no partial dependency, 3NF no transitive dependency. Interviewers often ask you to define exactly one, so know each crisply.

Q12. What is denormalization and when is it used?

Denormalization deliberately adds redundant data back into a normalized schema to speed up reads. Instead of joining five tables on every request, you might store a precomputed total or copy a frequently-read field so a single query hits one table and returns fast, avoiding the join cost entirely on that hot path.

You do it when read performance matters more than the cost of keeping duplicates in sync, common in reporting or read-heavy systems. The trade-off is real: now an update has to touch every copy, so you accept write complexity and the risk of inconsistency to buy faster reads. Normalize first, denormalize only where measurements justify it.

Key point: Frame it as a deliberate trade, faster reads for harder writes, not as 'bad design'. Saying you'd normalize first and denormalize with evidence signals maturity.

Q13. What is the difference between SQL and NoSQL databases?

SQL (relational) databases store structured data in tables with a fixed schema and give strong ACID transactions, so they fit data with clear relationships and correctness needs. NoSQL is a family of stores (document, key-value, wide-column, graph) that relax schema or transactional guarantees to gain flexibility or horizontal scale.

Pick relational when you need joins, complex queries, and transactional integrity, like orders and payments. Reach for NoSQL when the schema changes often, the data is naturally nested, or you need to scale writes across many machines beyond what one relational node handles. It's about fit, not one being better.

Key point: Avoid saying NoSQL 'has no schema' or 'doesn't scale' for SQL. The honest coverage names specific NoSQL types and matches each to a use case.

Watch a deeper explanation

Video: What is a Relational Database? (IBM Technology, YouTube)

Q14. How does a basic SELECT query work?

A SELECT names the columns you want, FROM names the table, WHERE filters which rows come back, ORDER BY sorts them, and LIMIT caps how many. The database reads the table (or uses an index), keeps rows matching the WHERE condition, then sorts and trims the result.

The order you write it isn't the order it runs: logically FROM and WHERE happen first to pick rows, then grouping and selection, then ORDER BY, then LIMIT. Knowing that logical order explains why you can't reference a SELECT alias in a WHERE clause in most databases.

sql
SELECT full_name, salary
FROM employees
WHERE department = 'Engineering'
ORDER BY salary DESC
LIMIT 10;

Key point: WHERE runs before SELECT (so aliases aren't visible in WHERE).

Q15. What is the difference between WHERE and HAVING?

WHERE filters individual rows before any grouping happens, so it decides which rows even enter the aggregation. HAVING filters groups after GROUP BY has aggregated them, so HAVING is where you put conditions on aggregate results like COUNT or SUM. Put simply, WHERE runs first on raw rows and HAVING runs last on grouped totals.

So to find departments with more than ten employees, you group by department and use HAVING COUNT(*) > 10, because the count only exists after grouping. You can't put that in WHERE. WHERE is per-row and runs first; HAVING is per-group and runs after aggregation.

sql
SELECT department, COUNT(*) AS headcount
FROM employees
WHERE active = true          -- filters rows first
GROUP BY department
HAVING COUNT(*) > 10;        -- filters groups after

Key point: The clean line is 'WHERE filters rows before grouping, HAVING filters groups after'. Trying to use an aggregate in WHERE is the mistake this checks for.

Q16. What does DISTINCT do, and how is it different from GROUP BY?

DISTINCT removes duplicate rows from a result so each combination of the selected columns appears exactly once. It's purely for deduplicating output when you just want the unique values, with no calculation involved. Selecting DISTINCT department from an employees table gives you one row per department, no matter how many people work in each.

GROUP BY also collapses duplicate values, but its purpose is to compute aggregates per group (counts, sums, averages). If you only want unique values with no aggregation, DISTINCT is clearer; if you need a per-group calculation, GROUP BY is the right tool. For a plain list of unique departments, DISTINCT; for a count of employees per department, GROUP BY.

Key point: The distinction is intent: DISTINCT for deduplication, GROUP BY for aggregation. Interviewers ask because people reach for GROUP BY when DISTINCT is simpler.

Q17. How does NULL behave in SQL?

NULL means 'unknown' or 'no value', not zero and not an empty string. Because it's unknown, any comparison with NULL using = or != returns NULL (treated as not true), so you test for it with IS NULL or IS NOT NULL, never = NULL.

NULL also affects aggregates and logic: most aggregate functions like SUM and AVG skip NULLs, COUNT(column) ignores them while COUNT(*) counts every row, and three-valued logic means a WHERE clause only keeps rows where the condition is truly TRUE. Forgetting this is a classic bug where rows silently drop out.

sql
-- wrong: returns no rows, = NULL is never true
SELECT * FROM employees WHERE manager_id = NULL;

-- right
SELECT * FROM employees WHERE manager_id IS NULL;

Key point: Say NULL is 'unknown' and that you test it with IS NULL. Explaining why = NULL fails is the deeper point this question is after.

Q18. What are constraints, and what types are there?

Constraints are rules the database enforces on column values so bad data can't get in. The main ones: NOT NULL (a value is required), UNIQUE (no duplicates), PRIMARY KEY (unique and not null), FOREIGN KEY (must reference an existing row), CHECK (a custom condition must hold), and DEFAULT (a value used when none is given).

The point is that the database, not just application code, guarantees integrity. A CHECK (salary > 0) stops a negative salary no matter which app inserts it, and a UNIQUE on email stops duplicates even if two requests race. Putting rules in the schema is more reliable than trusting every caller to validate.

Key point: Add that constraints enforce integrity at the database level, so a bug in one app can't corrupt data. That framing is stronger than just listing the constraint names.

Q19. Classify these commands: CREATE, INSERT, GRANT, COMMIT, TRUNCATE.

Here's the breakdown: CREATE is DDL because it defines structure. INSERT is DML because it changes data. GRANT is DCL because it controls access. COMMIT is TCL because it manages transactions. TRUNCATE is DDL, which surprises people who assume it's DML like DELETE, since both seem to remove rows.

TRUNCATE is DDL because it deallocates the table's data pages rather than deleting rows one at a time, so it's a structural operation that usually can't be filtered with WHERE and often can't be rolled back in the same way as DELETE. That difference is exactly why interviewers use it as the tricky one.

Key point: The gotcha is TRUNCATE being DDL, not DML. Getting that one right, with the 'it operates on structure' reason, is what this classification question is really testing.

Back to question list

DBMS Intermediate Interview Questions

Intermediate17 questions

For candidates with working experience: joins, indexing, isolation levels, transactions under concurrency, and the judgment questions that separate SQL writers from people who understand the engine.

Q20. What are the types of SQL joins?

INNER JOIN returns only rows that match in both tables. LEFT JOIN returns all rows from the left table plus matches from the right, filling NULLs where there's no match. RIGHT JOIN is the mirror, keeping all right-table rows. FULL OUTER JOIN keeps unmatched rows from both sides.

CROSS JOIN pairs every row of one table with every row of the other (a Cartesian product), and a self join joins a table to itself, useful for hierarchies like employees and their managers. The one interviewers probe most is LEFT JOIN, because it's how you find rows that have no match, like customers with zero orders.

JoinReturns
INNEROnly matching rows from both tables
LEFTAll left rows, matched right rows or NULL
RIGHTAll right rows, matched left rows or NULL
FULL OUTERAll rows from both, NULLs where no match
CROSSEvery combination (Cartesian product)

Key point: Be ready to write a LEFT JOIN with a WHERE right.id IS NULL to find unmatched rows. That anti-join pattern is the classic follow-up.

Watch a deeper explanation

Video: SQL Tutorial - Full Database Course for Beginners (freeCodeCamp.org, YouTube)

Q21. What is the difference between an inner join and an outer join, with an example?

An inner join keeps only rows that have a match on both sides, so any row without a partner simply disappears from the result. An outer join (LEFT, RIGHT, or FULL) keeps the unmatched rows from one or both tables and fills the missing side with NULL, so nothing gets silently dropped from the side you're protecting.

Say you join customers to orders. An inner join lists only customers who placed at least one order. A LEFT JOIN lists every customer, with NULLs for those who never ordered, which is exactly how you'd find customers who ordered nothing by adding WHERE orders.id IS NULL.

sql
-- customers who have never placed an order
SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

Key point: The anti-join (LEFT JOIN plus IS NULL) is the answer that impresses. It proves you understand outer joins, not just their definition.

Q22. What is an index and how does it speed up queries?

An index is a separate data structure, usually a B-tree, that stores the indexed column values in sorted order with pointers back to the rows. Instead of scanning every row to find matches, the database walks the sorted index to jump straight to the rows it needs, turning a linear scan into a logarithmic lookup.

That helps queries that filter, join, or sort on the indexed columns. The cost is on writes: every INSERT, UPDATE, or DELETE has to update the index too, and each index takes disk space. So indexes trade slower writes and more storage for faster reads, which is why you index the columns you query, not every column.

Key point: The B-tree and the write cost matters. Saying 'indexes make everything faster' is wrong; the trade against write speed is what separates users from operators.

Watch a deeper explanation

Video: B Trees and B+ Trees. How they are useful in Databases (Abdul Bari, YouTube)

Q23. What is the difference between a clustered and a non-clustered index?

A clustered index determines the physical order of rows in the table, so the table data itself is stored sorted by that index. There can be only one per table because rows can only be sorted one way, and it's usually the primary key. Looking up by it is fast because the row data is right there.

A non-clustered index is a separate structure holding the sorted key values with pointers to the actual rows. You can have many of them. A lookup finds the key in the index, then follows the pointer to fetch the row, one extra hop compared to a clustered index.

ClusteredNon-clustered
Row storageTable is physically sorted by itSeparate structure with pointers
Count per tableOneMany
LookupData is in the index leafIndex then pointer to row

Key point: The key facts are 'one clustered index, it sets physical row order' versus 'many non-clustered, they point to rows'. Terminology differs by engine, so say which you mean.

Q24. When can an index hurt performance?

Indexes slow down writes: every INSERT, UPDATE, or DELETE must maintain each index on the table, so a table with many indexes pays a write penalty on every change. They also consume disk and memory. On a write-heavy table, too many indexes is a real drag.

An index also doesn't help, or even gets skipped, when a query returns most of the table (a full scan is cheaper), when you filter on a column that isn't indexed, or when a function wraps the column (WHERE UPPER(name) = ...) so the plain index can't be used. Low-cardinality columns like a boolean rarely benefit either.

Key point: Naming that a function on the column (WHERE UPPER(col) = ...) defeats the index shows real query-tuning experience, not textbook knowledge.

Q25. What is a composite index and why does column order matter?

A composite index covers multiple columns in a defined order, say (last_name, first_name). It's stored sorted by the first column, then the second within that, like a phone book. It can serve queries that filter on the leading column, or the leading plus following columns.

Order matters because of that leftmost-prefix rule: an index on (a, b) helps queries filtering on a, or a and b, but not a query filtering only on b, since the index isn't sorted by b alone. So you put the column you filter on most, or the most selective one, first.

sql
CREATE INDEX idx_name ON people (last_name, first_name);

-- uses the index (leading column present)
SELECT * FROM people WHERE last_name = 'Rao';

-- can't use it efficiently (skips the leading column)
SELECT * FROM people WHERE first_name = 'Asha';

Key point: Explain the leftmost-prefix rule with an example. Knowing that an index on (a, b) won't help a query filtering only on b is the exact insight the question needs.

Q26. What are the SQL transaction isolation levels?

There are four standard levels, trading consistency for concurrency. Read uncommitted allows dirty reads (seeing another transaction's uncommitted changes). Read committed only sees committed data but allows non-repeatable reads. Repeatable read prevents non-repeatable reads but can still allow phantoms. Serializable is the strictest, behaving as if transactions ran one at a time.

Each level prevents more anomalies but reduces concurrency and can increase locking or aborts. Most databases default to read committed. You raise the level when correctness demands it, like preventing double-booking, and accept the performance cost.

LevelDirty readNon-repeatable readPhantom read
Read uncommittedPossiblePossiblePossible
Read committedPreventedPossiblePossible
Repeatable readPreventedPreventedPossible
SerializablePreventedPreventedPrevented

Key point: Know the table cold: which anomaly each level prevents. Interviewers hand you a scenario and ask the minimum level that fixes it.

Q27. What are dirty reads, non-repeatable reads, and phantom reads?

A dirty read is reading another transaction's uncommitted change that might later roll back, so you acted on data that never really existed. A non-repeatable read is reading the same row twice in one transaction and getting different values because another transaction committed an update in between.

A phantom read is running the same query twice and getting a different set of rows because another transaction inserted or deleted rows matching your condition. Non-repeatable is about a changed row; phantom is about new or removed rows appearing. Each stricter isolation level knocks out one more of these.

Key point: The subtle line is non-repeatable (a row's value changed) versus phantom (the set of rows changed). Mixing those two up is the most common error here.

Q28. What is a deadlock and how do databases handle it?

A deadlock happens when two transactions each hold a lock the other needs, so neither can proceed. Transaction A holds row 1 and wants row 2; transaction B holds row 2 and wants row 1. They wait on each other forever.

Databases detect deadlocks (usually with a wait-for graph) and break the cycle by aborting one transaction, the victim, which then rolls back and can retry. To reduce them, acquire locks in a consistent order across your code, keep transactions short, and use appropriate isolation. Your application should be ready to catch the deadlock error and retry.

Key point: Two things score: 'the database aborts a victim and it retries', and 'lock rows in a consistent order to prevent them'. The prevention half is what many candidates miss.

Q29. What is the difference between optimistic and pessimistic locking?

Pessimistic locking assumes conflicts are likely, so it locks a row the moment you read it and holds that lock until you finish, blocking anyone else who wants it. It's safe under heavy contention because nobody can slip in a conflicting change, but it reduces concurrency and raises the risk of deadlocks when transactions wait on each other.

Optimistic locking assumes conflicts are rare, so it doesn't lock. Instead it checks at write time whether the row changed since you read it (often via a version number or timestamp) and rejects the write if it did, asking you to retry. It scales better when conflicts are uncommon, which is why web apps favor it.

sql
-- optimistic: only update if the version hasn't changed
UPDATE accounts
SET balance = 900, version = version + 1
WHERE id = 1 AND version = 7;
-- if 0 rows updated, someone else changed it; retry

Key point: Frame the choice by contention: pessimistic for high conflict, optimistic for low. The version-column technique is the concrete detail that proves you've built it.

Q30. What is a stored procedure, and when would you use one?

A stored procedure is a named block of SQL (and procedural logic) saved in the database that you call by name. It can take parameters, run multiple statements, use control flow, and return results, all executing inside the database engine.

You'd use one to keep multi-step logic close to the data (fewer round trips), to enforce a consistent operation across different apps, or to grant callers permission to run the procedure without direct table access. The trade-off is that business logic in the database is harder to version, test, and move than logic in application code, so teams weigh that.

Key point: The downside too: procedures are harder to version and test than app code matters. A balanced answer beats treating them as purely good.

Q31. What is a view, and what is a materialized view?

A view is a saved query that behaves like a virtual table. It stores no data itself; every time you query the view, the underlying query runs against the base tables. Views simplify complex queries, present a consistent interface, and can restrict which columns a user sees.

A materialized view actually stores the query's result on disk, so reads are fast because there's no recomputation, but the data is a snapshot that goes stale and must be refreshed. Use a plain view for always-current data and simpler queries; use a materialized view when an expensive query is read often and slightly stale results are acceptable.

Key point: The core distinction is 'a view recomputes every time; a materialized view stores results and needs refreshing'. That trade, freshness versus speed, is the point.

Q32. How do aggregate functions work with GROUP BY?

Aggregate functions (COUNT, SUM, AVG, MIN, MAX) collapse many rows into one summary value. With GROUP BY, they compute one result per group instead of one for the whole table, so GROUP BY department with COUNT(*) gives a headcount per department.

A rule that trips people up: every column in the SELECT that isn't inside an aggregate must appear in GROUP BY, because the database needs to know how to collapse it. And to filter on an aggregate result you use HAVING, not WHERE, since the aggregate only exists after grouping.

sql
SELECT department, AVG(salary) AS avg_salary, COUNT(*) AS headcount
FROM employees
GROUP BY department
ORDER BY avg_salary DESC;

Key point: The rule that non-aggregated SELECT columns must be in GROUP BY. Getting a 'column must appear in GROUP BY' error is exactly what this checks you understand.

Q33. What is a subquery, and when would you use one over a join?

A subquery is a query nested inside another, in the WHERE, FROM, or SELECT clause. A correlated subquery references the outer query and runs per outer row; an uncorrelated one runs once. Subqueries read naturally for existence checks (WHERE EXISTS) or filtering against a computed set (WHERE id IN (SELECT ...)).

Joins are usually the better choice when you need columns from both tables in the output, and the planner often optimizes a join better than an equivalent correlated subquery. Reach for a subquery for readability on existence or set-membership tests; reach for a join when you're combining columns from multiple tables. Many are interchangeable, and a good optimizer treats them similarly.

Key point: Prefer EXISTS over IN when the subquery can return NULLs, because IN with a NULL in the list can silently return no rows. That nuance signals depth.

Q34. What is the difference between ACID and BASE?

ACID (Atomicity, Consistency, Isolation, Durability) is the strong-consistency model relational databases follow: a transaction fully commits or fully rolls back, and once it commits, the data is immediately consistent everywhere you read it. It prioritizes correctness over raw availability, which is exactly what you want for money, orders, and anything where a wrong answer is unacceptable.

BASE (Basically Available, Soft state, Eventual consistency) is the model many distributed NoSQL systems follow to stay available and scalable: the system is basically available, state can be in flux, and replicas become consistent eventually rather than instantly. It trades immediate consistency for availability and partition tolerance, which connects to the CAP theorem.

Key point: Link BASE to CAP: it's the availability-over-consistency choice for distributed systems. Naming that connection shows you understand why BASE exists, not just its acronym.

Q35. What is the CAP theorem?

The CAP theorem says a distributed data store can guarantee at most two of three properties at once: Consistency (every read sees the latest write), Availability (every request gets a response), and Partition tolerance (the system keeps working despite network splits between nodes).

Since network partitions are a fact of distributed systems, partition tolerance isn't really optional, so the real choice under a partition is between consistency and availability. A CP system refuses some requests to stay consistent; an AP system answers but may serve stale data. The theorem explains why distributed databases pick different trade-offs.

Key point: The sharp point is 'partitions happen, so you're really choosing C or A during one'. Saying you 'just pick two' without that nuance is the shallow version.

Q36. What does a query optimizer do, and what is an execution plan?

SQL is declarative: you say what data you want, not how to get it. The query optimizer decides how, choosing the access method (index scan vs full scan), the join order, and the join algorithm, using table statistics to estimate which plan is cheapest.

The execution plan is the chosen strategy, and you inspect it with EXPLAIN (or EXPLAIN ANALYZE to also run it and show real timings). Reading a plan tells you whether an index is used, where the row estimates are wrong, and which step is the bottleneck, which is the starting point for tuning a slow query.

sql
EXPLAIN ANALYZE
SELECT * FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC;

Key point: Say you'd run EXPLAIN ANALYZE and look for a sequential scan where you expected an index. That's the first move in any real query-tuning question.

Back to question list

DBMS Interview Questions for Experienced Engineers

Experienced14 questions

advanced rounds probe internals, scaling, and production scars. Expect every answer here to draw a follow-up about trade-offs and failure modes.

Q37. How does a B-tree index actually find a row?

A B-tree is a balanced tree kept shallow so lookups touch only a few nodes. The search starts at the root, which holds key ranges and pointers to child nodes, follows the child whose range contains the target key, and repeats down each level until it reaches a leaf node holding the sorted keys.

The leaf stores the key and a pointer to the actual row (or, in a covering index, the needed columns directly, so no table fetch is needed). Because the tree is balanced and wide, even a table with millions of rows is only a few levels deep, so a lookup is a handful of page reads instead of a full scan. That's the whole reason indexes work.

How a B-tree index lookup runs

1Enter at the root
start at the top node holding key ranges and child pointers
2Descend by range
at each level, follow the child whose range contains the key
3Reach a leaf
leaf nodes hold the sorted keys and pointers to the rows
4Fetch the row
follow the pointer to the table (or return it, if covered)

A B-tree stays shallow and balanced, so even a huge table is a handful of node reads deep. That's why an index turns a scan of millions of rows into a few page reads.

Key point: a covering index (all needed columns in the index, so the table read is skipped) is the senior detail that matters.

Q38. What is the difference between partitioning and sharding?

Partitioning splits one large table into smaller pieces within a single database, by range, list, or hash of a column. Queries and management get faster because the engine can prune to the relevant partitions, but it's still one database on one server.

Sharding spreads data across multiple independent databases on different servers, each holding a subset of the rows keyed by a shard key. It's how you scale writes and storage beyond one machine. The cost is real: cross-shard queries and transactions get hard, rebalancing is painful, and choosing a bad shard key creates hot spots. Partition first; shard only when one server genuinely can't hold the load.

PartitioningSharding
ScopeOne database, many piecesMany databases across servers
ScalesQuery and maintenance speedWrites and total storage
Hard partChoosing partition keyCross-shard queries, rebalancing

Key point: The production signal is 'partition within a node, shard across nodes' plus the warning that cross-shard joins and a bad shard key are where it hurts.

Q39. How does database replication work, and what are the trade-offs?

Replication keeps copies of the data on multiple servers. The common model is one primary handling writes that streams its changes to read replicas, which serve read traffic to scale reads and provide failover if the primary dies. Some systems support multi-primary, where more than one node accepts writes.

The core trade-off is synchronous versus asynchronous. Synchronous replication waits for a replica to confirm before committing, so no data is lost on failover but writes are slower. Asynchronous commits immediately and ships changes after, so it's fast but a replica can lag and a crash can lose the last changes. Reading from a lagging replica also means stale reads, which your app has to tolerate or route around.

Key point: The sync-vs-async trade and 'replica lag causes stale reads'. Those two are the follow-ups every replication question leads into.

Q40. What is MVCC and why do databases use it?

Multi-version concurrency control keeps multiple versions of a row so readers and writers don't block each other. When a transaction updates a row, the database writes a new version rather than overwriting the old one; each transaction sees the version consistent with when it started.

The payoff is that reads never block writes and writes never block reads, which gives high concurrency without heavy locking. It's how PostgreSQL and others implement isolation. The cost is that old row versions accumulate and must be cleaned up (vacuuming in PostgreSQL), and neglecting that cleanup causes table bloat and degraded performance.

Key point: the cleanup cost (dead tuples, vacuum, bloat) is what matters.

Q41. What is the N+1 query problem and how do you fix it?

The N+1 problem is running one query to fetch a list of N parent rows, then a separate query per parent to fetch its children, so you fire N+1 queries total. It usually comes from an ORM lazily loading a relationship inside a loop, and it quietly destroys performance as N grows.

You fix it by fetching the related data in one or two queries instead: a JOIN to pull parents and children together, or an eager-load/batch that fetches all children with a single WHERE child.parent_id IN (...). The instinct to build is spotting a query count that scales with row count, which is the tell that an N+1 is hiding.

sql
-- N+1: one query per parent (bad in a loop)
SELECT id FROM authors;               -- returns N authors
SELECT * FROM books WHERE author_id = ?;  -- run N times

-- fix: fetch all children in one query
SELECT * FROM books WHERE author_id IN (1,2,3, ...);

Key point: The tell is explicit: 'query count grows with the number of rows'. Naming the ORM lazy-loading cause shows you've debugged this in production.

Q42. Why do applications use a database connection pool?

Opening a database connection is expensive: a TCP handshake, authentication, and backend process or thread setup. Doing that per request adds latency and, worse, can exhaust the database's connection limit under load, because each open connection costs the server memory and resources.

A connection pool keeps a set of open connections and hands them out to requests, returning them to the pool when done instead of closing them. This caps concurrency at a safe number, reuses the expensive setup, and protects the database from being overwhelmed by thousands of short-lived connections. Sizing the pool right matters: too small starves the app, too large overloads the database.

Key point: The senior point is that a pool protects the database from connection exhaustion, not just that it's faster. Mentioning pool sizing as a real tuning decision helps.

Q43. When would you choose NoSQL over a relational database?

Choose NoSQL when the relational model fights your workload. If the schema changes constantly or data is naturally nested, a document store fits. If you need to scale writes across many machines beyond one relational node, a wide-column store handles that. For simple key-based lookups at huge volume, a key-value store is right. For heavily connected data with deep relationship queries, a graph database wins.

Stay relational when you need multi-row ACID transactions, complex ad-hoc queries with joins, and strong consistency, which is most business data. The honest answer resists 'NoSQL is more scalable' as a blanket claim; it names the specific store and the specific workload it fits, and admits you often use both (polyglot persistence) in one system.

Key point: Reflexively reaching for NoSQL to 'scale' is a red flag. Matching a specific NoSQL type to a specific workload, and defending when relational still wins, is the mature answer.

Q44. How do you decide when to denormalize a schema in production?

Start normalized, then denormalize only where measurements show a join or aggregation is a real bottleneck on a hot read path. The candidates are precomputed aggregates (a stored order total), duplicated fields to avoid a frequent join, or read-model tables built for a specific query.

The decision is a trade you own: you buy read speed by accepting write complexity, since every denormalized copy must be kept in sync, through the application, a trigger, or an async pipeline, and any of those can drift. So you denormalize when reads dominate, the query is proven slow, and you have a reliable way to keep the duplicate consistent. Guessing without profiling is how denormalization creates bugs instead of speed.

Key point: Insist on 'measure first, and have a sync mechanism for the duplicate'. Denormalizing on a hunch, with no plan to keep copies consistent, is the failure mode this probes.

Q45. Walk me through diagnosing a slow query in production.

First confirm which query and how slow, from the slow-query log or your monitoring, because you fix the query that actually hurts, not a guess. Then run EXPLAIN ANALYZE to see the real plan: look for a sequential scan where an index was expected, a bad join order, or row estimates far off from actual, which points at stale statistics.

From there the usual fixes are adding or correcting an index (including a composite or covering one), rewriting the query to be index-friendly (avoiding a function on the filtered column), updating statistics, or reducing the data touched. If the query is fine but the table is huge, partitioning or a read replica may be the answer. Verify with EXPLAIN ANALYZE again and confirm the improvement under real load.

Key point: The structure that scores: find the real slow query, read its plan, fix the specific cause, verify. Jumping straight to 'add an index' without EXPLAIN reads junior.

Q46. How do you maintain consistency across services in a distributed system?

A single-database ACID transaction doesn't stretch across independent services, so you can't just wrap them in one BEGIN/COMMIT. The common pattern is the saga: break the operation into a sequence of local transactions, each with a compensating action that undoes it, so if a later step fails you run the compensations to roll the whole thing back logically.

You also lean on idempotency (so retries are safe), the outbox pattern (write the event in the same local transaction as the data, then publish reliably) to avoid the dual-write problem, and accept eventual consistency where strong consistency isn't required. Two-phase commit exists but is avoided at scale because it blocks and couples services. The honest answer is that distributed consistency is about designing for eventual convergence and safe retries, not pretending you still have one big transaction.

Key point: Naming the saga pattern with compensating transactions, plus the outbox pattern for reliable events, is what a senior distributed-systems answer sounds like.

Q47. What kinds of locks do databases use, and how do they affect concurrency?

Databases use shared locks for reads (many readers can hold one at once) and exclusive locks for writes (only one holder, and it blocks readers and other writers). Locks also have granularity: row-level locks allow high concurrency but cost more to track, while table-level locks are cheap but block everyone.

Coarser or longer-held locks reduce concurrency and raise the chance of deadlocks, so you keep transactions short and touch as few rows as possible. Many modern databases use MVCC so that plain reads don't take blocking locks at all, and explicit locking (SELECT FOR UPDATE) is reserved for when you truly need to serialize access to specific rows.

sql
-- lock the row so a concurrent transaction can't change it
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
COMMIT;

Key point: Mention that MVCC lets reads avoid locks, and that SELECT FOR UPDATE is the tool for deliberate row-level serialization. That precision indicates production experience.

Q48. What is a write-ahead log and why does it matter for durability?

A write-ahead log (WAL) records every change to a durable log before applying it to the actual data files. The rule is log-first: the change is written and flushed to the WAL before the transaction is considered committed, so the record of what happened is safe on disk even if the data pages haven't been written yet.

This is what makes durability and crash recovery work. After a crash, the database replays the WAL to redo committed changes that hadn't reached the data files and to roll back uncommitted ones, restoring a consistent state. The WAL also underpins replication (replicas consume it) and point-in-time recovery. Without it, a crash mid-write could leave the database corrupt.

Key point: the WAL maps to three things: durability, crash recovery, and replication. Knowing it feeds replicas and PITR, not just recovery, is the senior-level detail.

Q49. How do you run a schema migration on a large table without downtime?

Use expand-and-contract so the schema stays compatible with both old and new code at every step. Expand: add the new column or table without touching the old, deploy code that writes to both and reads the old, backfill existing rows in batches to avoid a long lock, then switch reads to the new. Contract: once nothing uses the old shape, drop it in a later deploy.

The rules that keep it safe: never make a breaking change in one step while old code runs, avoid operations that hold a long exclusive lock on a big table (some ALTERs rewrite the whole table), backfill in small batches, and keep each step independently deployable and reversible. The point is decoupling the schema change from the code change so neither requires downtime.

Key point: Say 'expand-and-contract, backwards-compatible at every step, backfill in batches'. Proposing a single blocking ALTER on a huge live table is how this question fails.

Q50. Design question: model the schema for an e-commerce orders system.

Clarify first: do we track inventory, support multiple items per order, and need status history. Then lay out the core entities: customers, products, orders, and an order_items join table, because an order has many products and a product appears in many orders, a many-to-many that needs its own table. order_items holds order_id, product_id, quantity, and the unit price at purchase.

Add keys and constraints: primary keys on each table, foreign keys from orders to customers and from order_items to both orders and products, NOT NULL on required fields, and a CHECK that quantity is positive. Index the foreign keys and any column you filter on often (customer_id on orders, order status). The structure that scores is clarify, identify entities and relationships, resolve the many-to-many, then say which columns you'd key and index and why, each choice tied to a query the system will run.

sql
CREATE TABLE orders (
  id          BIGINT PRIMARY KEY,
  customer_id BIGINT NOT NULL REFERENCES customers(id),
  status      TEXT NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE order_items (
  order_id    BIGINT NOT NULL REFERENCES orders(id),
  product_id  BIGINT NOT NULL REFERENCES products(id),
  quantity    INT NOT NULL CHECK (quantity > 0),
  unit_cents  INT NOT NULL,          -- price captured at purchase
  PRIMARY KEY (order_id, product_id)
);

Key point: Open by asking clarifying questions, then resolve the order-to-product many-to-many with a join table. Capturing the price at purchase time is the detail interviewers love to see.

Back to question list

Relational vs NoSQL, and When Each Fits

A relational database stores data in tables with a fixed schema and enforces relationships and ACID transactions, so it fits data with clear structure and correctness needs like payments or orders. NoSQL is an umbrella for stores that relax some of that: document stores hold flexible JSON-like records, key-value stores map keys to blobs, wide-column stores scale writes across many machines, and graph databases model relationships as first-class edges. Each trades some guarantee for flexibility or scale. Knowing where each fits, and saying the trade-off out loud, is itself an interview signal.

Store typeData modelBest atWatch out for
Relational (RDBMS)Tables, fixed schema, SQLStructured data, joins, ACID correctnessRigid schema; scaling writes needs work
Document (NoSQL)JSON-like documentsFlexible or evolving schema, nested dataWeaker cross-document joins and transactions
Key-value (NoSQL)Key to value pairsCaches, sessions, very fast lookupsNo querying by value; you fetch by key
Wide-column (NoSQL)Rows with dynamic columnsHuge write volume, horizontal scaleQuery patterns must be designed up front
GraphNodes and edgesHighly connected data, relationship queriesOverkill when relationships are simple

How to Prepare for a DBMS Interview

Prepare in layers, and trade-offs out loud is the explanation path. Most DBMS rounds move from concept questions to a hands-on SQL task to a design discussion, so rehearse each stage rather than only reading answers.

  • Master your tier's concepts until you can explain them without notes, then read one tier up for the stretch questions.
  • Write real SQL against a local database (SQLite or PostgreSQL); joins, GROUP BY, and subqueries stick far faster when you run them.
  • Rehearse design answers with a structure: clarify the entities, sketch the tables and keys, The trade-off, then say how you'd index and query it.
  • Take the quiz on this page to find weak spots, then revisit those questions before the real round.

The typical DBMS interview flow

1Recruiter or phone screen
background, databases you know, a few concept checks
2Concept round
ACID, normalization, keys, indexes, joins, isolation
3Hands-on SQL
write queries, read an execution plan, debug a slow one
4Schema and design
model entities, pick keys and indexes, discuss trade-offs

Earlier rounds increasingly run as AI-driven technical interviews. The concepts on this page are what gets probed at every stage.

Test Yourself: DBMS Quiz

Ready to test your DBMS knowledge?

10 questions, about 6 minutes. Score 70% or higher to earn a shareable certificate.

10 questions Instant feedback Free certificate on 70%+

Frequently  Asked  Questions

Which DBMS topics should I prioritize before a technical round?

Prioritize the areas that change real decisions: fundamentals, practical tasks, debugging, trade-offs, and evidence. The highest-value questions are tied to a project example, a validation check, or a failure mode.

Do I need to know SQL to pass a DBMS interview?

Yes, at least the core: SELECT with WHERE, the join types, GROUP BY with aggregates, and subqueries. Many rounds hand you a schema and ask you to write a query live. You don't need every function memorized, but you should be able to reason through a join and an aggregation without freezing.

Which database do these answers assume?

The concepts are engine-agnostic, but SQL examples use standard syntax that runs on PostgreSQL, MySQL, and most relational databases. Where behavior differs (isolation defaults, index types), the answer says so. If your target company uses a specific engine, the ideas transfer; The one you'd map each concept to.

How long does it take to prepare for a DBMS interview?

If you already write SQL at work, one to two weeks of an hour a day covers this bank with practice queries. Starting colder, plan three to four weeks and build a small schema you can query daily. Reading answers without writing any SQL is how DBMS preparation quietly fails.

Do interviewers ask exactly these questions?

The concepts repeat far more reliably than the exact wording. Interviewers rephrase, chain follow-ups, and push toward whatever you claim confidence in. Prepare the underlying ideas, ACID, keys, normalization, indexing, joins, transactions, and the phrasing takes care of itself.

Is there a way to test my DBMS knowledge?

Yes. The quiz on this page scores you as you go and explains every answer, so you find your weak spots fast. Pass the threshold and you can download a shareable certificate with your name and score, free and with no sign-up. It's the quickest way to check yourself before the real round.

From the team that builds coding interviews

Hyring builds the AI Coding Interviewer that runs live technical rounds in 20+ languages for 5,000+ hiring teams. These DBMS questions and scoring notes reflect what actually gets asked and evaluated inside the interviews we host.

See how the AI Coding Interviewer works

Sources

Adithyan RKWritten by Adithyan RK
Surya N
Fact-checked by Surya N
Published on: 18 May 2026Last updated: 27 Jun 2026
Share: