01

What is the difference between a DBMS and a traditional file system?

Interview-ready answer

A traditional file system stores data in separate files that each application manages itself. A DBMS centrally manages structured data together with schemas/metadata, query languages and APIs, security, concurrency control, and recovery mechanisms. This central management reduces uncontrolled redundancy and lets multiple applications work with shared data reliably and consistently.

Understand it clearly

Core difference (short)

A traditional file system leaves data organization, access and integrity enforcement to individual applications. A DBMS places data under a database management layer that knows the data structure (metadata/schema) and provides operations and services for accessing and maintaining the data.

How file-based systems behave

In file-based systems each application usually decides how files are organized and how records are read or updated. If different applications maintain separate copies of the same information, those copies can easily become inconsistent. Recovery, concurrency and integrity are typically handled manually by application logic or ad-hoc procedures.

What a DBMS provides

A DBMS manages data together with rules and services so applications do not manipulate raw files directly. It exposes database operations or a query language and keeps metadata and schemas to know the structure of the data. Central management helps reduce uncontrolled redundancy and makes it easier to enforce rules consistently.

  • Metadata and schemas: DBMS knows data structure through metadata and schemas rather than leaving structure to each program.
  • Query/API access: Applications use query languages and database APIs instead of application-specific file handling.
  • Integrity rules: Built-in constraints and rules enforce data integrity rather than relying solely on application checks.
  • Concurrency control: DBMS provides built-in concurrency control so multiple users/applications can access data safely.
  • Security: Access is managed via users, roles, privileges and policies, beyond simple file-level permissions.
  • Recovery: DBMS uses logs, transactions and recovery mechanisms rather than manual backup/restore logic.

Why this matters (benefits)

Because a DBMS centralizes control, it enables controlled and reliable shared access for multiple applications, reduces redundancy, enforces consistency and integrity, and provides robust security, concurrency and recovery features that are cumbersome or fragile in file-based systems.

Quick comparison
BasisTraditional File SystemDBMS
Data accessApplication-specific file handlingQuery language and database APIs
StructureMostly managed by programsSchema and metadata managed by DBMS
IntegrityMostly application-level checksBuilt-in constraints and rules
ConcurrencyLimited or manually handledBuilt-in concurrency control
SecurityUsually file-level permissionsUsers, roles, privileges and policies
RecoveryManual backup/restore logicLogs, transactions and recovery mechanisms
RedundancyOften duplicated across filesCan be controlled through database design
02

What is data independence, and why is it important in database systems?

Interview-ready answer

Data independence means changes at one level of a database system can be made with little or no effect on the levels above it. It allows the database to evolve (for example, storage or schema changes) without forcing every application to be rewritten, improving maintainability.

DBMS Interview Questions diagram explaining What is data independence, and why is it important in database systems
Understand it clearly

Definition

Data independence means that changes at one level of a database system can be made with little or no effect on the levels above it.

Three levels of a database system

Database systems are commonly understood at three levels; each level separates concerns so changes below need not affect the ones above.

  • Physical level: Describes how data is actually stored (files, pages, indexes, storage structures).
  • Logical level: Describes tables, attributes, relationships, and constraints.
  • External (view) level: Contains the different views seen by users or applications.

Forms of data independence

There are two main forms of data independence, with examples of each.

  • Physical data independence: Storage details can change without changing the logical schema. Example: the DBMS may add an index or reorganize files without requiring application changes.
  • Logical data independence: The logical schema can change with minimal effect on user views or applications. Example: a table may be extended or reorganized while existing views continue to present the same required data.

Importance / Benefit

The major benefit is maintainability: database administrators can improve storage or evolve the schema without breaking every dependent program. Overall, data independence lets the database evolve without forcing every application to be rewritten. Physical data independence is generally easier to achieve than logical data independence because applications are more closely connected to the logical structure they use.

Quick comparison
BasisPhysical data independenceLogical data independence
DefinitionStorage details can change without changing the logical schema.Logical schema can change with minimal effect on user views or applications.
ExampleDBMS may add an index or reorganize files without requiring application changes.A table may be extended or reorganized while existing views continue to present the same required data.
Ease of achievementGenerally easier to achieve.Generally harder to achieve (applications are more closely connected to logical structure).
03

How is a database schema different from a database instance?

Interview-ready answer

A database schema is the design or structure of a database (tables, columns, data types, relationships, keys and constraints); a database instance is the actual data stored in that database at a particular moment. The schema is the blueprint and remains relatively stable, while the instance is the current content that changes when rows are inserted, updated, or deleted.

Understand it clearly

Schema — the design

The schema is the database's design or structure. It defines what objects exist and how they relate to each other.

  • Defines: table names, columns, data types, relationships, keys, and constraints

Instance — the current data

The instance is the actual data stored in the database at a particular moment in time. It consists of the rows and values that conform to the schema.

  • Contents: actual rows and values
  • Changes: modifies whenever rows are inserted, updated, or deleted

Concrete example

An example helps distinguish the two: the schema specifies the structure, while the instance holds specific records.

  • Schema example: Student(id, name, email)
  • Instance example: (101, Asha, a@x.com)

Analogy

A simple analogy: the schema is the blueprint of a building; the instance is the current state of what is inside that building.

Quick comparison
BasisSchemaInstance
MeaningDatabase structure or designCurrent data stored in the database
ContainsTables, columns, constraints, relationshipsActual rows and values
How often it changesRelatively rarelyFrequently
ExampleStudent(id, name, email)(101, Asha, a@x.com)
04

What is the difference between a primary key and a candidate key?

Interview-ready answer

A candidate key is any minimal set of attributes that can uniquely identify a row. The primary key is the one candidate key selected as the main identifier for that table. A table can have multiple candidate keys; the chosen one is the primary key and the others are alternate keys. Every primary key is a candidate key, but not every candidate key is chosen as the primary key. Primary key cannot contain NULL.

Understand it clearly

Definitions

Candidate key: Any minimal set of attributes that can uniquely identify a row in the table. 'Minimal' means no attribute can be removed without losing uniqueness.

Primary key: The single candidate key chosen by the database designer to serve as the table's main identifier.

Minimality and uniqueness

Each candidate key must uniquely identify rows and be minimal. There can be multiple candidate keys for a table when different attribute sets each uniquely identify rows.

The primary key is one of those candidate keys and therefore also uniquely identifies rows.

Example

Suppose a Student table has roll_no, email, and phone, and all three are individually unique. Then each of {roll_no}, {email}, and {phone} is a candidate key. The designer might choose roll_no as the primary key; the remaining candidate keys become alternate keys.

  • Candidate keys: {roll_no}, {email}, {phone}
  • Primary key: roll_no (chosen example)

Choosing a primary key

A good primary key is usually stable, unique, non-null, and preferably small. The primary key imposes a single primary key constraint on the table.

Remember: every primary key is a candidate key, but not every candidate key is selected as primary; the unselected candidate keys are often called alternate keys.

  • Good primary key traits: stable, unique, non-null, preferably small
Quick comparison
BasisCandidate keyPrimary key
MeaningAny minimal unique identifierChosen candidate key used as main identifier
Number in a tableCan be multipleOnly one primary key constraint
UniquenessMust uniquely identify rowsMust uniquely identify rows
NULLCandidate keys conceptually identify rows uniquelyPrimary key cannot contain NULL
Exampleroll_no, email, phoneroll_no
05

What is referential integrity, and how does a DBMS enforce it?

Interview-ready answer

Referential integrity ensures that a foreign key in a child table either refers to a valid row in the parent table or follows the allowed NULL/default rules. A DBMS enforces it using foreign key constraints and defined referential actions (RESTRICT/NO ACTION, CASCADE, SET NULL, SET DEFAULT) to prevent orphan records and control behavior when referenced parent rows are updated or deleted.

Understand it clearly

Definition

Referential integrity ensures that a foreign key in a child table either refers to a valid row in the parent table or follows the allowed NULL/default rules.

Enforcement via Foreign Key Constraints

A DBMS enforces referential integrity using foreign key constraints. Consider Students(student_id, name) and Enrollments(student_id, course_id). The student_id in Enrollments is a foreign key that refers to Students.

If an application tries to insert an enrollment for a student that does not exist, the DBMS can reject the operation. This prevents orphan records. The same issue appears when a referenced parent row is updated or deleted; the foreign key can define what the DBMS should do.

Common Referential Actions

The foreign key constraint can specify a referential action to determine how the DBMS handles updates or deletes of the referenced parent row.

  • RESTRICT / NO ACTION: prevent the parent update/delete when matching child rows exist.
  • CASCADE: automatically apply the related update/delete to child rows.
  • SET NULL: keep the child row but clear the foreign key, if NULL is allowed.
  • SET DEFAULT: replace the foreign key with its defined default value, if the DBMS/schema supports it.

Purpose

Referential integrity keeps relationships between tables valid, so the database cannot silently contain references to records that do not exist.

06

You are designing a college database. How would you model students, courses, and enrollments?

Interview-ready answer

Model Student and Course as separate entities and use Enrollment as a bridge (junction) table to represent the many-to-many relationship. Example schema: Student(student_id PK, name, email, ...), Course(course_id PK, title, credits, ...), Enrollment(student_id FK, course_id FK, semester, grade, enrollment_date, ...). Enrollment holds relationship-specific attributes (e.g., grade). For keys: (student_id, course_id, semester) can be a composite PK, or Enrollment can have an enrollment_id PK plus a uniqueness constraint to prevent duplicate enrollments.

DBMS Interview Questions diagram explaining You are designing a college database. How would you model students, courses, and enrollments
Understand it clearly

Design overview

Student and Course are modeled as separate entities. Because a student can take many courses and a course can have many students, their relationship is many-to-many.

Introduce an Enrollment table as a bridge (junction) table to convert the many-to-many into two one-to-many relationships.

Table examples

Provide simple table structures that capture primary attributes and the enrollment relationship.

  • Student: student_id PK, name, email, ...
  • Course: course_id PK, title, credits, ...
  • Enrollment: student_id FK, course_id FK, semester, grade, enrollment_date, ...

Relationship and attributes

Enrollment acts as the bridge table: one Student can have many Enrollment rows, and one Course can have many Enrollment rows.

Relationship-specific information (for example, grade) belongs in Enrollment because it applies to a particular student's enrollment in a particular course.

Keys and uniqueness

Decide how to identify Enrollment rows based on requirements. Two common approaches are described below.

If you need to prevent duplicate enrollments, enforce uniqueness either via a composite primary key or a uniqueness constraint.

  • Composite key option: (student_id, course_id, semester) could form a composite primary key.
  • Surrogate key option: Enrollment could have its own enrollment_id primary key plus a uniqueness constraint to prevent duplicate enrollments.
Quick comparison
BasisComposite key (student_id, course_id, semester)Surrogate PK (enrollment_id) + uniqueness constraint
Primary key(student_id, course_id, semester) is the PKenrollment_id is the PK
Uniqueness enforcementUniqueness enforced implicitly by the composite PKUniqueness enforced by an explicit uniqueness constraint on (student_id, course_id, semester)
07

Why is a many-to-many relationship usually resolved using an associative entity?

Interview-ready answer

Because relational tables represent relationships through keys, an associative entity converts a many-to-many (M:N) relationship into two one-to-many (1:N) relationships. This avoids repeating course or student data in the other table, prevents update/repetition problems, gives each specific student–course pairing its own row, allows the relationship to store attributes (e.g., grade, semester, enrollment_date, status), and enables foreign key constraints and indexes for integrity and efficient queries.

DBMS Interview Questions diagram explaining Why is a many-to-many relationship usually resolved using an associative entity
Understand it clearly

Core reason

Relational tables model relationships using keys and foreign keys. An associative entity (associative table) represents each M:N link as its own row, turning one M:N relationship into two 1:N relationships. This is the primary reason many-to-many relationships are resolved with an associative entity.

How it works

The associative table contains the foreign keys of both participating entities; each row represents one specific relationship instance. For example, with students and courses, an associative entity named Enrollment holds the student and course foreign keys so Student -> Enrollment is one-to-many and Course -> Enrollment is one-to-many.

  • Relationship mapping: Student -> Enrollment is one-to-many.
  • Relationship mapping: Course -> Enrollment is one-to-many.

Why not store repeated data inside one side

If course information were repeatedly stored inside Student rows, or student information repeatedly stored inside Course rows, the design would create repetition and update problems. Repeated values make rows less clean and lead to difficulties maintaining correct, consistent data.

Benefits and enforcement

An associative entity centralizes the relationship and provides several practical advantages: it gives the relationship its own place to store attributes that belong to the relationship itself, foreign key constraints can enforce valid references to both entities, and indexes can be created on the relationship keys for efficient querying. Overall this produces cleaner rows, stronger integrity, and simpler queries than trying to represent the M:N relationship directly with repeated values.

  • Relationship attributes: Enrollment can store grade, semester, enrollment_date, status, or other relationship data.
  • Referential integrity: Foreign key constraints can enforce valid Student and Course references.
  • Performance: Indexes can be created on the relationship keys for efficient querying.
Quick comparison
BasisRepeating data inside one table (direct M:N representation)Associative entity (Enrollment)
RepresentationStore repeating student or course information inside the other tableSeparate associative table with foreign keys to both participating tables
Repetition and updatesCreates repetition and update problemsEliminates repetition by centralizing relationships
Relationship attributesHard to store without duplicationCan store attributes such as grade, semester, enrollment_date, status
Referential integrityDifficult to enforce consistentlyEnforced by foreign key constraints to Student and Course
Querying and performanceQueries can be more complex and inefficient due to repeated valuesIndexes can be placed on relationship keys for efficient querying
Row cleanliness and integrityProduces messy rows and weaker integrityProduces cleaner rows, stronger integrity, and simpler queries
08

What are insertion, update, and deletion anomalies?

Interview-ready answer

Insertion, update, and deletion anomalies are problems that arise when multiple independent facts are stored together in one poorly designed table. They cause unnecessary restrictions, repeated updates, or accidental loss of information. For example, in a StudentCourse table that stores Student, Course, and Teacher, course and teacher information get repeated across many rows. The three common anomalies are: • Insertion anomaly: you cannot store one fact without also having unrelated data (e.g., you may be unable to add a new course until at least one student enrolls). • Update anomaly: the same fact appears in many rows, so changing a teacher’s name requires updating every repeated row or data becomes inconsistent. • Deletion anomaly: deleting a row to remove one fact can accidentally remove another fact (e.g., deleting the last student enrolled in a course may also remove the only stored information about that course and its teacher). Normalization reduces these anomalies by separating independent facts into related tables.

Understand it clearly

Overview and motivating example

Insertion, update, and deletion anomalies are problems caused by storing multiple independent facts in one poorly designed table. They lead to unnecessary restrictions, repeated updates, or accidental loss of information.

A common motivating example is a StudentCourse table that contains Student, Course, and Teacher. If the same course is taken by many students, the course and teacher information is repeated across many rows, which creates the conditions for the three anomalies described below.

  • Table example: StudentCourse table with Student, Course, and Teacher — course and teacher details repeated across rows.

Insertion anomaly

An insertion anomaly occurs when you cannot store one fact without also having unrelated data. The table design forces you to include data that may not yet exist or is irrelevant to the fact you want to record.

  • Example: You may be unable to add a new course until at least one student enrolls in it.

Update anomaly

An update anomaly happens when the same fact appears in many rows. Changing that fact requires updating every repeated row; missing even one update creates inconsistent data across the table.

  • Example: If a teacher's name changes, every row containing that teacher must be updated. Missing a row yields inconsistent data.

Deletion anomaly

A deletion anomaly arises when deleting a row to remove one fact inadvertently removes another independent fact because they were stored together in the same row.

  • Example: Deleting the last student enrolled in a course may also remove the only stored information about that course and its teacher.

How normalization helps

Normalization reduces insertion, update, and deletion anomalies by separating independent facts into related tables. By storing each fact in the appropriate relation (for example: Students, Courses, Teachers, and Enrollment), repetition is minimized and the anomalies are avoided.

Quick comparison
BasisEffect / problemConcrete example
Insertion anomalyCannot store one fact without unrelated data; forces unwanted dependencies when adding data.Unable to add a new course until at least one student enrolls in it.
Update anomalyThe same fact appears in many rows, so updates must be repeated across rows or inconsistency results.If a teacher's name changes, every repeated row must be updated; missing one creates inconsistent data.
Deletion anomalyDeleting a row to remove one fact accidentally removes another fact because they were stored together.Deleting the last student enrolled in a course may remove the only stored information about that course and its teacher.
09

A table stores customer details and repeated order information. How would you decide whether normalization is required?

Interview-ready answer

I would examine the table for repeated customer information, repeating groups, mixed facts, functional dependencies, and insertion/update/deletion anomalies. If those problems exist, normalize by separating stable entities (e.g., Customer, Order, OrderItem) so each attribute depends on the correct key. Denormalization can be applied later only as a measured optimization for read performance, not as the default for transactional design.

Understand it clearly

Decision criteria — what to check

I would check whether the table contains repeated customer information, repeating groups, mixed facts, functional dependencies, or insertion/update/deletion anomalies. If it does, normalization is usually needed.

  • Repeated values: The same customer name or phone appears many times when a customer places several orders.
  • Repeating groups: Order or item information is stored in repeated columns or rows instead of separate rows/entities.
  • Mixed facts: Attributes with different dependencies (customer-level vs order-level vs order-item-level) are stored in one table.
  • Functional dependencies: Attributes should be tested for what key they actually depend on (customer, order, or order-item).
  • Anomalies: Insertion, update, or deletion anomalies indicate the need for normalization.

Analyze attribute dependencies

Ask what each attribute actually depends on. Use the dependencies to determine proper grouping of attributes.

  • Customer-level: Customer details depend on the customer (e.g., name, phone).
  • Order-level: Order details depend on the order (e.g., order_date, order_id linked to customer).
  • Order-item-level: Item quantities depend on a particular order-item combination (order_id + item_id).

Example normalized design

A cleaner design would usually separate the stable entities so each table represents a single level of dependency.

  • Customer: Customer(customer_id, name, phone, ...)
  • Order: Order(order_id, customer_id, order_date, ...)
  • OrderItem: OrderItem(order_id, item_id, quantity, ...)

When to consider denormalization

I would strongly consider normalization when the design causes repeated values, frequent update problems, or mixed facts that have different dependencies. Denormalization can sometimes be justified later for measured read-performance needs, but it should be a deliberate optimization rather than the starting point for a transactional design.

10

What is the difference between Third Normal Form and BCNF?

Interview-ready answer

BCNF is a stronger (stricter) form of 3NF. In 3NF a functional dependency X -> Y is allowed if X is a super key OR Y is a prime attribute (an attribute that belongs to at least one candidate key). In BCNF every non‑trivial functional dependency X -> Y requires X to be a super key. Therefore every BCNF relation is in 3NF, but a relation can be in 3NF and still violate BCNF. BCNF typically removes more redundancy but decomposing to BCNF can sometimes make it harder to preserve all original functional dependencies.

Understand it clearly

Core distinction (short)

BCNF is stricter than Third Normal Form. The difference is in the allowed determinants for functional dependencies: 3NF permits a dependency X -> Y when X is a super key or Y is a prime attribute; BCNF requires X to be a super key for every non‑trivial dependency.

Formal rule comparison

State the rules precisely to contrast them.

  • 3NF rule: For a functional dependency X -> Y, either X is a super key OR Y is a prime attribute.
  • BCNF rule: For a functional dependency X -> Y, X must be a super key (for every non‑trivial FD).

Why a relation can be in 3NF but not BCNF

A prime attribute is an attribute that belongs to at least one candidate key. Because 3NF allows Y to be prime, some dependencies that do not have a super key as determinant are still permitted. That allowance is exactly why a relation can satisfy 3NF yet violate BCNF.

Practical implications and trade-offs

BCNF removes more redundancy because every determinant must uniquely identify a row (be a super key). However, achieving BCNF by decomposing a relation can sometimes make it harder to preserve all original functional dependencies in the decomposed tables. In contrast, 3NF is less strict and is often easier to use when dependency preservation is important.

  • Redundancy: 3NF can allow some remaining redundancy; BCNF usually removes more redundancy.
  • Dependency preservation: 3NF is often easier to preserve dependencies; BCNF may sacrifice dependency preservation.
Quick comparison
BasisThird Normal Form (3NF)Boyce‑Codd Normal Form (BCNF)
Rule for X -> YX is a super key OR Y is a prime attributeX must be a super key
StrictnessLess strictMore strict
RelationshipA relation may be in 3NF but not in BCNFEvery BCNF relation is in 3NF
RedundancyCan allow some remaining redundancyUsually removes more redundancy
Trade-offOften easier to preserve dependenciesMay sacrifice dependency preservation
11

When can denormalization be a better design choice than normalization?

Interview-ready answer

Denormalization can be a better choice when the system is read-heavy and repeated joins or aggregations are a proven performance bottleneck. It intentionally introduces controlled redundancy to make reads faster and is commonly considered for reporting, dashboards, materialized summaries, analytics, or other workloads where reads greatly outnumber writes, but it requires active consistency management and should be based on actual query measurements and access patterns.

Understand it clearly

When to consider denormalization

Denormalization is appropriate when a system is read-heavy and repeated joins or aggregations are a proven performance bottleneck. Instead of normalizing strictly for minimal redundancy, you introduce controlled duplication to reduce the amount of runtime work required for queries.

What denormalization does

In a normalized database, information is split into well-structured related tables to improve consistency and reduce duplication, but complex reports may require many joins. Denormalization stores some repeated or precomputed information so a query can read fewer tables or perform less work at runtime, making reads faster at the expense of redundancy.

Common use cases (examples)

Denormalization is commonly considered for workloads where reads greatly outnumber writes and query latency matters. Typical examples include:

  • Reporting systems: Precompute or duplicate fields to avoid heavy joins when generating reports.
  • Dashboards: Store aggregates or summary fields so dashboard queries return quickly.
  • Materialized summaries: Maintain denormalized summary tables to serve aggregated queries.
  • Analytics: Duplicate or pre-aggregate analytic dimensions to speed up queries.
  • Read-heavy workloads: Any workload measured to be read-dominant where join cost is a bottleneck.

Trade-offs and cautions

The main trade-off is consistency management: if the same fact is stored in multiple places, every copy must remain synchronized. Writes may require updating repeated data, increasing complexity. Therefore, denormalization should be based on actual query measurements and access patterns and not used blindly.

Quick comparison
BasisNormalized designDenormalized design
RedundancyLowHigher and controlled
ReadsMay require more joinsCan be faster
WritesUsually easier to keep consistentMay require updating repeated data
StorageUsually lowerUsually higher
Best fitTransactional consistencyMeasured read-heavy workloads
12

What do the ACID properties guarantee in a database transaction?

Interview-ready answer

ACID properties guarantee that database transactions behave reliably under errors, concurrency, and system failures by enforcing Atomicity, Consistency, Isolation, and Durability.

Understand it clearly

Direct answer

ACID properties ensure that database transactions behave reliably even when there are errors, concurrent users, or system failures. Together they guarantee that each transaction is processed safely and predictably.

The four ACID properties

Each letter of ACID describes one guarantee a transaction system must provide.

  • Atomicity: A transaction is all-or-nothing. Either every required operation succeeds, or the entire transaction is rolled back.
  • Consistency: A successful transaction moves the database from one valid state to another while respecting defined rules and constraints.
  • Isolation: Concurrent transactions should behave safely so that intermediate operations do not incorrectly interfere with each other.
  • Durability: Once a transaction commits, its changes must survive failures such as a process or system crash.

Concrete example

A bank transfer illustrates how the properties interact: debiting Account A and crediting Account B are treated as one transaction.

  • Atomicity in the example: If the credit to Account B fails, Atomicity prevents only the debit from remaining (the whole transaction is rolled back).
  • Isolation in the example: Isolation protects the transfer from conflicting concurrent work so intermediate states are not observed by other transactions.
  • Consistency and Durability in the example: Consistency keeps database rules valid during the transfer, and Durability ensures that a committed transfer is not lost after a crash.

Overall guarantee

Together, Atomicity, Consistency, Isolation and Durability ensure transactions are reliable and predictable despite errors, multiple concurrent users, or system failures.

13

Two users try to update the same account balance at the same time. What concurrency problem can occur?

Interview-ready answer

Lost update — it occurs when two transactions read the same old value and both write new values, so one transaction's result overwrites the other.

DBMS Interview Questions diagram explaining Two users try to update the same account balance at the same time. What concurrency problem can occur
Understand it clearly

What the problem is

The main problem is a lost update. It happens when two transactions read the same old value and then both write new values, causing one transaction's result to overwrite the other.

Concrete example (account balance)

Suppose an account balance is 100. Transaction T1 reads 100 and plans to subtract 10, while T2 also reads 100 and plans to subtract 20. T1 writes 90. Then T2, still using the old value 100, writes 80. The final value becomes 80 even though both changes together should have produced 70. The update performed by T1 has effectively disappeared.

  • Step 1: T1 reads balance = 100
  • Step 2: T2 reads balance = 100
  • Step 3: T1 writes 90
  • Step 4: T2 writes 80
  • Result: Expected combined result = 70; Actual final value = 80

How a DBMS can prevent or detect it

A DBMS can prevent or detect lost updates using suitable isolation, locking, MVCC conflict checks, or atomic update statements that modify the value without relying on a stale application-side copy.

  • Isolation: Use appropriate transaction isolation to avoid concurrent reads/writes causing lost updates.
  • Locking: Acquire locks so one transaction updates the value exclusively while others wait.
  • MVCC conflict checks: Detect conflicting concurrent writes via multiversion concurrency control checks.
  • Atomic updates: Use atomic update statements that modify the value on the server side rather than relying on a stale client-side copy.
14

What is the difference between a serial schedule and a serializable schedule?

Interview-ready answer

A serial schedule runs one transaction completely before another begins. A serializable schedule may interleave operations from multiple transactions, but its final effect must be equivalent to some correct serial order.

Understand it clearly

Definitions

A serial schedule runs one transaction completely before another begins. A serializable schedule may interleave operations from multiple transactions, but its final effect must be equivalent to some correct serial order.

Properties and trade-offs

A serial schedule is simple and safe because transactions never overlap. The disadvantage is poor concurrency: one transaction may keep others waiting even when some operations could safely run together. A serializable schedule allows concurrency while preserving the correctness expected from serial execution.

  • Advantage: Serializable schedules provide higher concurrency while maintaining correctness equivalent to some serial order.
  • Disadvantage: Serial schedules have low concurrency because transactions run one after another.

Relationship and correctness

Therefore, a schedule can be non-serial but still serializable. Not every concurrent schedule is serializable. The DBMS needs concurrency-control techniques to make sure interleaving does not produce an invalid result.

Practical implication

Use serial schedules when simplicity and absolute isolation are required, accepting low concurrency. Use serializable schedules to allow transactions to overlap while ensuring that the final state is equivalent to some serial execution, typically enforced by the DBMS’s concurrency-control mechanisms.

Quick comparison
BasisSerial ScheduleSerializable Schedule
InterleavingNoAllowed
ExecutionOne transaction completes before the next startsTransactions can overlap
Correctness goalNaturally follows a serial orderEquivalent to some serial order
ConcurrencyLowHigher
RelationshipAlways serializableMay be serial or non-serial; not every concurrent schedule is serializable.
15

What is a dirty read, and which isolation level allows it?

Interview-ready answer

A dirty read occurs when one transaction reads a value written by another transaction before that second transaction has committed. The READ UNCOMMITTED isolation level allows dirty reads. Example: T1 updates a balance from 400 to 500 but has not committed; T2 reads 500 while T1 is still active; if T1 later rolls back to 400, T2 has used a value that never became permanent (dirty data). READ COMMITTED and stronger isolation levels prevent dirty reads by ensuring a transaction does not read another transaction's uncommitted changes.

Understand it clearly

Definition

A dirty read happens when one transaction reads a value written by another transaction that has not yet committed. The read value may be rolled back later, so it is not guaranteed to be permanent or correct.

Isolation level that allows it

READ UNCOMMITTED is the standard isolation level that can allow dirty reads. Under this level a transaction may observe changes made by other transactions before those changes are committed.

Concrete example (two transactions)

This sequence shows how a dirty read can occur:

  • Step 1: T1: Update balance = 500 (original was 400) — not committed yet.
  • Step 2: T2: Read balance = 500 (reads T1's uncommitted change).
  • Step 3: T1: ROLLBACK — database value returns to 400; T2 used a value (500) that never became permanent.

Prevention

READ COMMITTED and stronger standard isolation levels prevent dirty reads by ensuring a transaction does not read another transaction's uncommitted changes.

Quick comparison
BasisREAD UNCOMMITTEDREAD COMMITTED and stronger
Dirty reads allowed?Yes — can read another transaction's uncommitted changes.No — prevents reading uncommitted changes.
16

A transaction reads the same row twice but gets different values. Which anomaly has occurred?

Interview-ready answer

Non-repeatable read — a transaction reads the same row twice and gets different committed values because another transaction updated and committed that row between the two reads.

Understand it clearly

Direct answer

This is a non-repeatable read. It occurs when a transaction reads the same row twice and gets different committed values because another transaction updated that row and committed between the two reads.

Example

T1 reads an employee salary as 50,000. T2 updates that same salary to 60,000 and commits. When T1 reads the row again, it now sees 60,000. The same query against the same row has produced two different values during one transaction.

  • Scenario: T1 reads 50,000 → T2 updates to 60,000 and commits → T1 reads 60,000

How this differs from other anomalies

This is different from a dirty read because the second value is committed. It is also different from a phantom read, which normally concerns rows being added or removed from a result set that matches a condition.

Mitigation / isolation

Repeatable Read or a stronger isolation level is generally used when the same row must remain stable for repeated reads within a transaction, although exact behavior depends on the DBMS implementation.

17

What is a deadlock in DBMS, and how can the database detect it?

Interview-ready answer

A deadlock occurs when two or more transactions wait for resources held by one another in a cycle so none can continue. A DBMS can detect deadlocks by building a wait-for graph (transactions as nodes; an edge T1 -> T2 means T1 is waiting for a resource held by T2) and checking the graph for cycles. If a cycle is found, the transactions in that cycle are deadlocked. Typical resolution is: detect the cycle, choose a victim transaction, abort or roll it back, release its locks, and allow the remaining transaction(s) to continue; the victim may be retried later. Some systems also use timeouts or prevention strategies.

DBMS Interview Questions diagram explaining What is a deadlock in DBMS, and how can the database detect it
Understand it clearly

Definition

A deadlock occurs when two or more transactions each wait for resources held by the other(s) in a cycle, so none of the transactions can make progress.

Deadlock detection — wait-for graph

The DBMS can detect deadlocks by constructing a wait-for graph and checking it for cycles. In this graph, each active transaction is represented as a node, and directed edges show waiting relationships.

  • Edge meaning: An edge T1 -> T2 means T1 is waiting for a resource currently held by T2. A cycle in the graph indicates a deadlock.

Example

For example, T1 holds a lock on resource A and requests B, while T2 holds B and requests A. T1 waits for T2 and T2 waits for T1, producing a cycle in the wait-for graph and thus a deadlock.

Resolution steps

Once a cycle is detected, the DBMS resolves the deadlock by selecting one or more transactions as victims and rolling them back so other transactions can proceed.

  • Detect cycle: Identify the cycle in the wait-for graph.
  • Choose victim: Select one transaction in the cycle to abort (victim selection policy may vary).
  • Abort/rollback: Abort or roll back the chosen victim transaction.
  • Release locks: Release the victim's locks so other transactions can acquire the needed resources.
  • Continue: Allow the remaining transaction(s) involved in the cycle to continue; the victim may be retried later.

Other approaches

In addition to cycle detection, some systems employ timeouts or prevention strategies to avoid or reduce deadlocks, but cycle detection via a wait-for graph is the standard detection technique described above.

18

How does Two-Phase Locking help maintain serializability?

Interview-ready answer

Two-Phase Locking (2PL) enforces conflict serializability by forcing each transaction to have a growing phase (it may acquire locks but not release any) followed by a shrinking phase (it may release locks but not acquire any). Because every transaction follows this ordering rule, resulting schedules are conflict-serializable. Common variants: Basic 2PL (growing then shrinking), Strict 2PL (hold write/exclusive locks until commit or rollback, preventing access to uncommitted writes and simplifying recovery), and Conservative 2PL (attempt to acquire all required locks before execution to avoid deadlocks, at the cost of reduced concurrency).

DBMS Interview Questions diagram explaining How does Two-Phase Locking help maintain serializability
Understand it clearly

Core mechanism

Two-Phase Locking controls when a transaction may acquire and release locks by dividing its execution into two phases. This enforced ordering prevents interleavings that would violate conflict-serializability.

  • Growing phase: The transaction may acquire new locks, but it cannot release any lock.
  • Shrinking phase: The transaction may release locks, but it cannot acquire any new lock.

Why this yields serializability

Because every transaction follows the same ordering rule (acquire-only then release-only), the set of schedules produced is conflict-serializable. The enforced order prevents cycles of conflicting operations that would make a schedule non-serializable.

Common variants

Several variants of 2PL adjust lock-holding behavior to trade off concurrency, deadlock risk, and recovery complexity.

  • Basic 2PL: Growing phase followed by shrinking phase.
  • Strict 2PL: Hold write/exclusive locks until commit or rollback.
  • Conservative 2PL: Acquire required locks before execution begins.

Effects and trade-offs

Basic 2PL guarantees serializability but can still allow deadlocks because transactions may wait for each other's locks. Strict 2PL is a stronger variant that prevents other transactions from reading or overwriting uncommitted writes and simplifies recovery by holding exclusive locks until commit or rollback. Conservative 2PL attempts to avoid deadlocks by acquiring all required locks up front, but doing so can reduce concurrency.

Quick comparison
BasisVariantDetails
Basic 2PLGrowing phase followed by shrinking phaseGuarantees conflict serializability but can still allow deadlocks
Strict 2PLHold write/exclusive locks until commit or rollbackPrevents other transactions from reading/overwriting uncommitted writes and simplifies recovery
Conservative 2PLAcquire required locks before execution beginsAvoids deadlocks but may reduce concurrency
19

How does MVCC improve concurrency compared with strict lock-based execution?

Interview-ready answer

MVCC (Multi-Version Concurrency Control) improves concurrency by keeping multiple versions of rows so readers can often read a consistent snapshot without waiting for writers. Updates create new versions while older committed versions remain visible to transactions using a snapshot, which greatly reduces read-write blocking—especially in read-heavy workloads—though concurrent writers can still conflict and old versions require cleanup.

Understand it clearly

Short answer

MVCC (Multi-Version Concurrency Control) improves concurrency by preserving multiple versions of rows so readers can read a consistent snapshot without blocking writers. This reduces read-write blocking common under strict lock-based execution and is especially effective for read-heavy workloads.

How MVCC works

When a row is updated under MVCC, the system creates a new row version while preserving the older committed version. A transaction reading from a snapshot continues to see the appropriate older committed version even while another transaction creates a new version. Visibility rules and snapshots determine which version each transaction sees, allowing readers to proceed without acquiring locks that block writers.

  • Readers: Read from a snapshot and often do not block or get blocked by writers.
  • Updates: Create new row versions instead of modifying the existing version in place.
  • Visibility rules: Snapshots and visibility rules decide which version a transaction can see.
  • Cleanup: Old versions are eventually removed when no active transaction can still need them.

Benefits and costs

MVCC greatly reduces read-write blocking compared with strict lock-based execution and typically yields higher concurrency for read-heavy workloads. The trade-offs are additional storage for extra versions and the need for version cleanup; strict locking trades those costs for simpler state but can cause more waiting and lower concurrency under contention.

  • Benefit: Readers continue without waiting for writers, reducing contention.
  • Cost: Extra row versions and background cleanup (garbage collection) are required.

Limits and conflicts

MVCC does not eliminate all conflicts. Concurrent writers can still conflict and the DBMS must detect or serialize those cases. Old versions must be retained until no active transaction can need them, and are removed only afterward.

Quick comparison
BasisStrict lock-based executionMVCC
Read/write interactionReaders may wait for writers or vice versaReaders often use snapshots without blocking writers
UpdatesModify data under locksCreate new row versions
ConcurrencyCan be lower under contentionOften higher for read-heavy workloads
Main costWaiting/blockingExtra versions and cleanup
Consistency mechanismLock ownershipVisibility rules and snapshots
20

A table has millions of records and searches are becoming slow. What DBMS feature would you consider first?

Interview-ready answer

First consider adding an index on the columns used by the slow query—especially those in selective WHERE conditions, JOINs, and sometimes ORDER BY or GROUP BY. Use EXPLAIN (or the DBMS execution plan) to verify index usage. Keep in mind selectivity, composite indexes when multiple columns are used together, and that an index is a strong first consideration but not an automatic cure; other causes (poor joins, returning too much data, outdated statistics, locking, insufficient memory) can also cause slowness.

Understand it clearly

Primary feature to consider

The first DBMS feature to consider is an index on the columns used by the slow query. Without a useful index the DBMS may perform a full table scan and examine millions of rows even when only a small number match the query. An index creates an additional search structure that helps the DBMS reach matching rows much more quickly.

Which columns to index

Focus indexing effort on columns that the query actually uses. This includes columns in WHERE conditions, columns used to join tables, and sometimes columns used for ORDER BY or GROUP BY.

  • WHERE conditions: Index columns used in selective WHERE predicates.
  • JOIN columns: Index columns that are used in joins between tables.
  • Sorting/Grouping: Consider indexes on columns used in ORDER BY or GROUP BY where appropriate.
  • Composite indexes: Use composite (multi-column) indexes when multiple columns are frequently used together in queries.

How to verify and choose

Use the execution plan (for example EXPLAIN) to verify whether the DBMS is using the index and to identify where the real cost occurs. The correct index depends on the actual query pattern; an index that looks reasonable may not be used if it doesn't match how the query is written or if statistics are outdated.

  • Execution plan: Run EXPLAIN to see if the index is used and to find hot spots.
  • Selectivity: Be aware that an index on a column with very low selectivity may provide little benefit.

Caveats and other causes of slowness

An index is a strong first consideration but not an automatic cure. Slow performance can also come from poor joins, returning too much data, outdated statistics, locking, insufficient memory, or other causes. Use profiling and the execution plan to diagnose whether indexing or other changes are needed.

21

Why are B+ trees commonly used for database indexes?

Interview-ready answer

B+ trees are used for database indexes because they remain balanced and shallow (high fan-out), which keeps page accesses low and lookup cost predictable as the index grows. Internal nodes store search keys to guide navigation while actual row references or data entries live at the leaf level; leaves are usually linked in key order, enabling both fast point lookups and efficient range or ordered scans.

DBMS Interview Questions diagram explaining Why are B+ trees commonly used for database indexes
Understand it clearly

Balanced, predictable height

All leaves in a B+ tree are at the same depth, so lookup cost remains predictable as the index grows. This predictable, balanced height is important because disk or page I/O is much more expensive than in-memory comparisons.

High fan-out and shallow trees

Database pages can hold many keys and child pointers, so each internal node can have many children (high fan-out). That high fan-out keeps the tree shallow, which reduces the number of page accesses required to find a key.

Leaf-level storage and linked leaves

Search keys are stored in internal nodes to guide navigation, while the actual row references or data entries are kept at the leaf level. Leaf nodes are usually linked in key order, so once the DBMS finds the first matching leaf entry it can continue through neighboring leaves efficiently.

Supported operations

Because of the structure above, B+ trees support both fast point lookups and efficient sequential access patterns, making them practical for many database workloads.

  • Equality search: Navigate quickly to a key.
  • Range search: Find the starting key and scan linked leaves.
  • ORDER BY / ordered scans: Keys are maintained in sorted order for efficient ordered retrieval.
  • Large datasets: Balanced height keeps search cost predictable as the index grows.
22

What is the difference between clustered and non-clustered indexing?

Interview-ready answer

A clustered index determines the table's physical row order according to the index key, while a non-clustered index is a separate ordered structure that contains keys and references (row locators) to the actual table rows. A table usually has only one clustered index but can have many non-clustered indexes; the clustered index’s leaf level contains the actual data rows, whereas a non-clustered index’s leaf level contains row locators or key references.

Understand it clearly

Core difference

A clustered index determines the order or organization of table rows according to the index key, i.e., it is tied to the table's main physical or clustered storage order. A non-clustered index is a separate structure that contains keys and references that lead to the actual table rows and does not reorganize the table in the same way.

Key properties (concise)

  • Data organization: Clustered: Determines table's row/order organization. Non-clustered: Separate index structure.
  • Number per table: Clustered: Usually one. Non-clustered: Can be many.
  • Leaf level: Clustered: Contains/represents the actual data rows or clustered entries. Non-clustered: Contains row locator / key reference.
  • Range scans: Clustered: Often very efficient when range follows clustered key. Non-clustered: Can be efficient but may require additional row lookups.
  • Use case: Clustered: Range access and ordered retrieval. Non-clustered: Alternate lookup paths.

Summary and practical note

Because table rows can only have one main physical organization at a time, a table usually has only one clustered index (or clustered storage order) but can have multiple non-clustered indexes to support different search patterns. This allows efficient ordered retrieval when the access pattern matches the clustered key and alternate lookup paths via non-clustered indexes when it does not.

Implementation caveat

Exact storage behavior varies between DBMS products, but the important concept is that a clustered index is tied to the table's main row organization, while a non-clustered index is an additional lookup structure.

Quick comparison
BasisClustered IndexNon-Clustered Index
Data organizationDetermines table's row/order organizationSeparate index structure
Number per tableUsually oneCan be many
Leaf levelContains/represents the actual data rows or clustered entriesContains row locator / key reference
Range scansOften very efficient when range follows clustered keyCan be efficient but may require additional row lookups
Use caseRange access and ordered retrievalAlternate lookup paths
Storage behaviorTied to the table's main physical organizationMaintains its own ordered key structure and points to corresponding rows
23

Why can adding too many indexes reduce database performance?

Interview-ready answer

Too many indexes can reduce performance because every write must update additional index structures; indexes also consume disk space and memory and increase maintenance overhead. They speed reads by reducing scans, but each INSERT, UPDATE or DELETE may require creating, removing, or changing index entries. Create indexes only for proven query patterns and important access paths rather than indexing every column automatically.

Understand it clearly

Direct answer

Indexes mainly improve reads by reducing the amount of data the DBMS must scan. However, an index is an extra data structure that must stay synchronized with the table, so adding many indexes increases the work the DBMS must do for writes and for ongoing maintenance.

How indexes affect write performance

Every write operation can require index maintenance because the index entries must reflect the current table state. The more indexes a table has, the more work each write may require.

  • INSERT: New entries may need to be created in every relevant index.
  • UPDATE: Changed indexed values may require index entries to be removed and reinserted (or otherwise updated).
  • DELETE: When a row is deleted, corresponding index entries must be removed from relevant indexes.

Resource and maintenance costs

Indexes consume storage and memory and increase maintenance effort. These costs matter because index pages compete for cache and disk, and more indexes increase the scope of rebuilds, statistics gathering, and fragmentation management.

  • Storage: Each index occupies additional pages/disk space.
  • Memory/cache: Frequently used index pages compete for memory.
  • Maintenance: Rebuilds, statistics and fragmentation work increase as the number of indexes grows.

Recommended approach

The best approach is to create indexes for proven query patterns and important access paths rather than indexing every column automatically. Prioritize indexes that provide measurable read benefits that justify the added write and maintenance cost.

24

A server crashes while a transaction is partially completed. How does log-based recovery restore consistency?

Interview-ready answer

After a crash, log-based recovery examines the transaction log to determine which changes to REDO and which to UNDO. Committed transactions are preserved (their updates are REDONE if necessary), while partial updates from uncommitted transactions are removed (UNDONE). Checkpoint information reduces how much of the log must be scanned. This process ensures Atomicity (no partial transactions remain) and Durability (committed work can be restored even if pages were not yet written).

Understand it clearly

Overview

After a server crash, log-based recovery uses records written to the transaction log during normal processing to restore database consistency. The process distinguishes committed work, which must be preserved, from incomplete uncommitted work, which must be removed.

Role of the log

During normal transaction processing the DBMS records enough information in a log to describe important changes. Depending on the recovery design, log records may contain before values, after values, or other information needed to repeat or reverse an operation.

After a crash, the database examines these log records and the recorded transaction states to determine the appropriate recovery actions.

  • Before values: May be recorded so operations can be reversed (UNDO).
  • After values: May be recorded so operations can be repeated (REDO).
  • Other information: Any additional metadata needed to repeat or reverse an operation.

Recovery actions: REDO and UNDO

The recovery process uses the log to perform REDO for committed work that might not have been written to durable storage, and UNDO for partial updates from transactions that did not commit before the crash.

  • Committed transaction: Its updates may need REDO if the log shows they committed but some modified data pages had not yet been written to durable storage.
  • Uncommitted transaction: Its partial updates must be UNDO so incomplete work does not remain in the database.
  • Checkpoint information: Helps the DBMS reduce how much of the log must be examined during recovery.

Correctness and implementation note

This recovery process enforces Atomicity because incomplete transactions do not remain partially applied, and Durability because committed work can be restored even if the latest data pages were not fully written before the crash.

The exact recovery algorithm differs across DBMS implementations, but REDO of committed work when needed and UNDO of incomplete work is the central idea.

25

What is Write-Ahead Logging, and why must the log be written before the data page?

Interview-ready answer

Write-Ahead Logging (WAL) requires the relevant log record to be made durable before the corresponding modified data page is written to disk. This guarantees the DBMS has the recovery information available if a crash happens and ensures commit durability: the log describing a change must be safely stored before the dirty page may reach durable storage.

Understand it clearly

Definition

Write-Ahead Logging (WAL) requires the relevant log record to be made durable before the corresponding modified data page is written to disk. Database pages are usually modified in memory first; WAL mandates that the log describing those changes be stored durably before any changed (dirty) page is allowed to reach durable storage.

Why the log must be written first

If the system crashes after a data page has been written but before the log exists, the DBMS could see a changed page without having enough information to understand, undo, or redo that change. Writing the log first guarantees the DBMS has the recovery information available to correctly perform REDO and/or UNDO after a crash.

How WAL works (steps)

WAL lets the DBMS defer flushing dirty pages to disk but enforces the ordering that the log record describing a change is made durable first.

  • Step 1: Transaction changes a page in memory.
  • Step 2: Corresponding log record is written and made durable first.
  • Step 3: The data page may be flushed later.
  • Step 4: After a crash, the durable log can be used for REDO and/or UNDO as required.

Commit durability and recovery

Before the DBMS reports a transaction as committed, the log records required to recover that commit must be durable. WAL is a foundation of reliable crash recovery because it gives the DBMS a durable history of changes before those changes can appear permanently in database pages.