DBMS interviews test your understanding of database fundamentals — normalization, transactions, keys, indexing, and concurrency control. This guide covers 50 of the most common DBMS interview questions with clear answers, useful tables, and examples.
Quick reference
| Topic | Most asked questions |
|---|---|
| Basics | DBMS vs RDBMS, data models, schemas |
| ER model | entities, attributes, relationships, cardinality |
| Keys | primary, foreign, candidate, super, composite |
| Normalization | 1NF–BCNF, functional dependencies |
| SQL | DDL/DML/DCL, joins, subqueries |
| Transactions | ACID, isolation levels, savepoints |
| Concurrency | locks, deadlocks, 2PL, timestamp ordering |
| Indexing | B-tree, clustered vs non-clustered, composite |
| Storage | file organization, buffer management |
| Advanced | CAP theorem, views, stored procedures, triggers |
Basics
1. What is a DBMS? What are its advantages over a file system?
A Database Management System (DBMS) is software that stores, manages, and retrieves structured data efficiently. It provides an interface between users/applications and the physical data.
Advantages over a file system:
| Disadvantage of file system | How DBMS solves it |
|---|---|
| Data redundancy and inconsistency | Centralised storage, normalisation |
| Difficult data access | Query language (SQL) |
| Data isolation (multiple formats) | Unified schema |
| Integrity problems (no constraints) | Integrity constraints enforcement |
| Atomicity failures | Transaction management |
| Concurrent-access anomalies | Concurrency control |
| Security problems | Authentication, authorisation, views |
2. What is the difference between DBMS and RDBMS?
| Feature | DBMS | RDBMS |
|---|---|---|
| Data storage | Files, hierarchical, network | Tables (relations) |
| Relationships | Not enforced | Foreign keys enforce relationships |
| Normalisation | Not supported | Supported |
| ACID properties | Partial support | Full ACID compliance |
| Query language | Varies | SQL standard |
| Examples | IMS, XML databases | MySQL, PostgreSQL, Oracle, SQL Server |
3. What is a schema? Difference between logical and physical schema?
A schema is the overall design or structure of a database.
| Schema type | What it describes | Who sees it |
|---|---|---|
| Physical schema | How data is stored on disk (files, indexes, storage structures) | DBA |
| Logical (conceptual) schema | Tables, columns, data types, constraints, relationships | Developer |
| External (view) schema | Subset of the database visible to a specific user or application | End user |
This three-level architecture is called the ANSI/SPARC architecture. It provides data independence — changes at one level don't affect levels above it.
4. What is data independence?
Data independence means the ability to change the schema at one level without changing the schema at the next higher level.
- Physical data independence: change the physical storage structure (e.g., swap disk layout, add index) without changing the logical schema.
- Logical data independence: change the logical schema (e.g., add a column to a table) without changing external schemas (views seen by applications).
Logical data independence is harder to achieve than physical.
5. What are the different types of data models?
| Data model | Structure | Example systems |
|---|---|---|
| Relational | Tables (relations) with rows and columns | MySQL, PostgreSQL, Oracle |
| Hierarchical | Tree structure, parent–child | IBM IMS |
| Network | Graph, records linked by pointers | IDMS |
| Object-oriented | Objects with attributes and methods | db4o |
| Document | JSON/BSON documents | MongoDB, CouchDB |
| Key-value | Key → value pairs | Redis, DynamoDB |
| Column-family | Column groups stored together | Cassandra, HBase |
| Graph | Nodes and edges | Neo4j, ArangoDB |
| Entity-relationship | Conceptual design model | Used in design phase |
ER Model
6. What is an Entity-Relationship (ER) diagram?
An ER diagram is a conceptual data model that shows entities (things), their attributes (properties), and the relationships between them. It is used in the design phase before creating the actual database.
Key symbols:
| Symbol | Shape | Meaning |
|---|---|---|
| Entity | Rectangle | A real-world object (e.g., Student, Course) |
| Weak entity | Double rectangle | Depends on another entity for identification |
| Attribute | Ellipse | Property of an entity (e.g., Name, Age) |
| Key attribute | Underlined ellipse | Uniquely identifies an entity |
| Multivalued attribute | Double ellipse | Can have multiple values (e.g., Phone numbers) |
| Derived attribute | Dashed ellipse | Computed from other attributes (e.g., Age from DOB) |
| Relationship | Diamond | Association between entities |
| Weak relationship | Double diamond | Relationship involving a weak entity |
7. What is a weak entity? Give an example.
A weak entity cannot be uniquely identified by its own attributes alone — it depends on a strong entity (its owner) for identification.
- A weak entity has a partial key (discriminator) that is unique only within the context of its owner.
- The relationship connecting a weak entity to its owner is called an identifying relationship.
Example: Order_Item is a weak entity. An order item is identified by its item_number only within a specific Order. Without the Order_ID, item_number = 3 is meaningless.
Order (strong) ——<< Order_Item (weak)
Order_ID (PK) item_number (partial key)
quantity
8. Explain the different types of attributes in ER modelling.
| Attribute type | Description | Example |
|---|---|---|
| Simple (atomic) | Cannot be divided further | Age, Gender |
| Composite | Composed of multiple sub-attributes | Name (First + Last) |
| Single-valued | Holds one value per entity | Date of Birth |
| Multivalued | Holds multiple values | Phone numbers, Hobbies |
| Derived | Calculated from other attributes | Age (from DOB) |
| Key attribute | Uniquely identifies the entity | Student_ID |
| Null attribute | May have no value in some instances | Middle name |
9. What are the different types of relationships and their cardinalities?
Cardinality defines how many instances of one entity relate to instances of another.
| Cardinality | Notation | Example |
|---|---|---|
| One-to-one (1:1) | ───────── |
Person ↔ Passport |
| One-to-many (1:N) | ─────< |
Department ↔ Employees |
| Many-to-one (N:1) | >───── |
Employees ↔ Department |
| Many-to-many (M:N) | >─────< |
Students ↔ Courses |
Participation constraints:
- Total participation (double line): every entity in the set must participate in at least one relationship. (e.g., every Employee must work in a Department)
- Partial participation (single line): some entities may not participate. (e.g., some Employees may not manage a project)
10. What is a ternary relationship?
A ternary relationship involves three entities participating simultaneously.
Example: A Supplier supplies a Part to a Project. This three-way association cannot be correctly decomposed into three binary relationships without losing information.
Supplier ─────── Supplies ─────── Part
│
Project
Keys
11. What are the different types of keys in a relational database?
| Key type | Definition | Example |
|---|---|---|
| Super key | Any set of attributes that uniquely identifies a tuple | {Student_ID}, {Student_ID, Name}, {Email} |
| Candidate key | Minimal super key (no redundant attributes) | {Student_ID}, {Email} |
| Primary key | Chosen candidate key used to identify rows | Student_ID |
| Alternate key | Candidate keys not chosen as primary key | |
| Foreign key | Attribute(s) referencing the primary key of another table | Course_ID in Enrollment |
| Composite key | Primary key made of two or more attributes | (Student_ID, Course_ID) in Enrollment |
| Surrogate key | System-generated artificial key | Auto-increment ID |
| Natural key | Key derived from real-world data | SSN, ISBN |
12. What is a foreign key? What are referential integrity constraints?
A foreign key is an attribute (or set of attributes) in one table that references the primary key of another table.
Referential integrity means: a foreign key value must either match an existing primary key value in the referenced table, or be NULL (if allowed).
ON DELETE / ON UPDATE actions:
| Action | Behaviour |
|---|---|
CASCADE |
Delete/update referencing rows automatically |
SET NULL |
Set FK to NULL when referenced row is deleted |
SET DEFAULT |
Set FK to its default value |
RESTRICT |
Prevent deletion/update if referenced rows exist |
NO ACTION |
Same as RESTRICT (checked at end of transaction) |
CREATE TABLE Enrollment (
student_id INT REFERENCES Student(id) ON DELETE CASCADE,
course_id INT REFERENCES Course(id) ON DELETE RESTRICT,
PRIMARY KEY (student_id, course_id)
);
13. What is the difference between a primary key and a unique key?
| Feature | Primary key | Unique key |
|---|---|---|
| NULL values | Not allowed | Allowed (one NULL per column in most RDBMS) |
| Number per table | Only one | Multiple |
| Purpose | Row identification | Enforce uniqueness |
| Index created | Clustered (by default in most RDBMS) | Non-clustered |
| Foreign key target | Yes | Yes (in most RDBMS) |
Normalization
14. What is normalization? Why is it needed?
Normalization is the process of organizing a relational database to reduce data redundancy and improve data integrity by decomposing tables into smaller, well-structured tables.
Problems caused by redundancy (update anomalies):
| Anomaly | Description | Example |
|---|---|---|
| Insertion anomaly | Can't add data without adding unrelated data | Can't add a Department without an Employee |
| Deletion anomaly | Deleting a row removes unintended data | Deleting last employee in dept removes dept info |
| Update anomaly | Same data in multiple rows must be updated everywhere | Changing a department name requires many row updates |
15. Explain 1NF, 2NF, 3NF, and BCNF.
First Normal Form (1NF):
- Each column holds atomic (indivisible) values.
- No repeating groups or arrays.
- All rows are unique.
VIOLATION: Student(ID, Name, Courses) ← Courses is multivalued
FIX: Student(ID, Name) + Enrollment(Student_ID, Course)
Second Normal Form (2NF):
- Must be in 1NF.
- No partial dependency — every non-key attribute depends on the whole composite primary key, not just part of it.
VIOLATION: Enrollment(Student_ID, Course_ID, Student_Name)
Student_Name depends only on Student_ID (partial dependency)
FIX: Enrollment(Student_ID, Course_ID, Grade)
Student(Student_ID, Student_Name)
Third Normal Form (3NF):
- Must be in 2NF.
- No transitive dependency — non-key attributes must not depend on other non-key attributes.
VIOLATION: Employee(Emp_ID, Dept_ID, Dept_Name)
Dept_Name depends on Dept_ID, which is not the PK
FIX: Employee(Emp_ID, Dept_ID)
Department(Dept_ID, Dept_Name)
Boyce-Codd Normal Form (BCNF):
- Stronger version of 3NF.
- For every non-trivial functional dependency
X → Y,Xmust be a super key. - Resolves anomalies that 3NF misses when a table has multiple overlapping candidate keys.
VIOLATION: Course(Student, Subject, Teacher)
Teacher → Subject (but Teacher is not a super key)
FIX: Split into two tables:
Teacher_Subject(Teacher, Subject)
Student_Teacher(Student, Teacher)
16. What is a functional dependency?
A functional dependency X → Y means: the value of attribute set X uniquely determines the value of attribute set Y.
Types of functional dependencies:
| Type | Definition | Example |
|---|---|---|
| Trivial | Y is a subset of X | {A, B} → {A} |
| Non-trivial | Y is not a subset of X | Student_ID → Name |
| Fully functional | X → Y and removing any attribute from X breaks the dependency | (Student_ID, Course_ID) → Grade |
| Partial | X → Y but a proper subset of X also determines Y | (Student_ID, Course_ID) → Student_Name |
| Transitive | X → Z via another attribute: X → Y → Z | Emp_ID → Dept_ID → Dept_Name |
| Multivalued | X →→ Y (used in 4NF) | Student →→ Phone, Student →→ Activity |
17. What are 4NF and 5NF?
Fourth Normal Form (4NF):
- Must be in BCNF.
- No multivalued dependency:
X →→ Ymeans X determines a set of Y values, independent of other attributes.
VIOLATION: Employee(Emp_ID, Skill, Language)
Emp_ID →→ Skill and Emp_ID →→ Language independently
FIX: Employee_Skill(Emp_ID, Skill)
Employee_Language(Emp_ID, Language)
Fifth Normal Form (5NF) / Project-Join Normal Form (PJNF):
- Must be in 4NF.
- No join dependency that is not implied by candidate keys — the table cannot be losslessly decomposed into smaller tables.
- Rarely needed in practice.
18. What is denormalization? When would you use it?
Denormalization is the intentional introduction of redundancy into a normalized schema to improve read performance at the cost of write complexity and storage.
When to denormalize:
- Read-heavy OLAP/reporting workloads where joins are expensive.
- Aggregated data in dashboards (pre-computed totals).
- Tables that are read millions of times per second but updated rarely.
- Data warehouses (star/snowflake schemas are intentionally denormalized).
Trade-offs:
| Aspect | Normalized | Denormalized |
|---|---|---|
| Read performance | Slower (joins) | Faster (fewer joins) |
| Write performance | Faster (one place to update) | Slower (update redundant copies) |
| Storage | Less | More |
| Data integrity | High | Risk of inconsistency |
| Best for | OLTP | OLAP / read-heavy |
SQL
19. What are DDL, DML, DCL, and TCL commands?
| Category | Full name | Commands | Purpose |
|---|---|---|---|
| DDL | Data Definition Language | CREATE, ALTER, DROP, TRUNCATE, RENAME | Define/modify schema |
| DML | Data Manipulation Language | SELECT, INSERT, UPDATE, DELETE | Manipulate data |
| DCL | Data Control Language | GRANT, REVOKE | Control access permissions |
| TCL | Transaction Control Language | COMMIT, ROLLBACK, SAVEPOINT | Manage transactions |
-- DDL
CREATE TABLE Student (id INT PRIMARY KEY, name VARCHAR(100));
-- DML
INSERT INTO Student VALUES (1, 'Alice');
UPDATE Student SET name = 'Alicia' WHERE id = 1;
-- DCL
GRANT SELECT ON Student TO analyst_role;
-- TCL
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
20. Explain all types of SQL JOINs.
| JOIN type | Returns |
|---|---|
INNER JOIN |
Rows matching in both tables |
LEFT JOIN |
All rows from left table + matching rows from right (NULLs for no match) |
RIGHT JOIN |
All rows from right table + matching rows from left |
FULL OUTER JOIN |
All rows from both tables (NULLs where no match) |
CROSS JOIN |
Cartesian product — every left row × every right row |
SELF JOIN |
A table joined to itself |
NATURAL JOIN |
INNER JOIN on all columns with the same name (use with caution) |
-- Find all students and their enrolled courses (if any)
SELECT s.name, c.title
FROM Student s
LEFT JOIN Enrollment e ON s.id = e.student_id
LEFT JOIN Course c ON e.course_id = c.id;
21. What is the difference between DELETE, TRUNCATE, and DROP?
| Command | Removes | WHERE clause | Transaction | Rollback | Resets auto-increment | DDL/DML |
|---|---|---|---|---|---|---|
DELETE |
Rows | Yes | Yes (logged) | Yes | No | DML |
TRUNCATE |
All rows | No | Implicit commit (in most RDBMS) | Usually No | Yes | DDL |
DROP |
Entire table (structure + data) | N/A | Implicit commit | No | N/A | DDL |
22. What is a subquery? What are correlated subqueries?
A subquery (inner query) is a SELECT statement nested inside another SQL statement.
-- Simple subquery: find students who scored above average
SELECT name FROM Student
WHERE marks > (SELECT AVG(marks) FROM Student);
A correlated subquery references a column from the outer query — it executes once per row of the outer query.
-- Correlated: find each student's highest score
SELECT s.name, s.marks
FROM Student s
WHERE s.marks = (
SELECT MAX(s2.marks)
FROM Student s2
WHERE s2.class = s.class -- references outer query's column
);
| Type | Executes | Performance |
|---|---|---|
| Simple subquery | Once | Fast |
| Correlated subquery | Once per outer row | Can be slow — prefer JOIN or window function |
23. What is a view? What are the advantages and limitations of views?
A view is a named virtual table defined by a SELECT query. It does not store data itself (unless materialized).
CREATE VIEW ActiveStudents AS
SELECT id, name, email FROM Student WHERE status = 'active';
Advantages:
- Security: expose only specific columns/rows to users.
- Simplicity: hide complex JOIN logic behind a simple name.
- Logical data independence: application queries the view; underlying table changes don't break the app (if view is updated).
- Consistent data representation: business logic in one place.
Limitations:
- Performance: each query against the view re-executes the underlying SELECT.
- Not all views are updatable (views with GROUP BY, DISTINCT, aggregates, UNION, subqueries are typically read-only).
- Cannot have indexes directly (except materialized views).
24. What is the difference between a view and a materialized view?
| Feature | View | Materialized view |
|---|---|---|
| Data stored | No (query executed each time) | Yes (results cached on disk) |
| Query speed | Depends on base tables | Fast (pre-computed) |
| Freshness | Always current | Stale until refreshed |
| Refresh options | N/A | Manual, scheduled, or on commit |
| Storage cost | None | Storage for cached data |
| Use case | Abstraction, security | Reporting, aggregations, data warehouses |
Transactions
25. What are ACID properties?
ACID ensures reliable transaction processing in a DBMS.
| Property | Meaning | Example guarantee |
|---|---|---|
| Atomicity | All operations in a transaction succeed or none do | Bank transfer: debit + credit both happen, or neither |
| Consistency | Transaction brings the DB from one valid state to another | Account balance never goes negative (constraint) |
| Isolation | Concurrent transactions don't interfere with each other | Two users booking the last seat don't both succeed |
| Durability | Committed transactions survive system failures | After COMMIT, data is on disk even if server crashes |
How ACID is implemented:
| Property | Mechanism |
|---|---|
| Atomicity | Write-ahead logging (WAL), undo logs |
| Consistency | Integrity constraints, triggers, application logic |
| Isolation | Concurrency control (locks, MVCC) |
| Durability | Write-ahead logging, checkpoints, replication |
26. What are the four transaction isolation levels?
Isolation levels control how concurrent transactions see each other's uncommitted changes.
Concurrency problems:
| Problem | Description |
|---|---|
| Dirty read | Reading uncommitted data that may be rolled back |
| Non-repeatable read | Same row gives different values in same transaction |
| Phantom read | Same query returns different set of rows in same transaction |
| Lost update | Two transactions overwrite each other's update |
Isolation levels (ANSI SQL):
| Isolation level | Dirty read | Non-repeatable read | Phantom read | Performance |
|---|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible | Highest |
| READ COMMITTED | Prevented | Possible | Possible | High |
| REPEATABLE READ | Prevented | Prevented | Possible | Medium |
| SERIALIZABLE | Prevented | Prevented | Prevented | Lowest |
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN;
-- All reads in this transaction see a consistent snapshot
COMMIT;
27. What is a savepoint?
A savepoint marks a point within a transaction to which you can roll back partially without aborting the entire transaction.
BEGIN;
INSERT INTO orders VALUES (1, 'Alice', 500);
SAVEPOINT sp1;
INSERT INTO orders VALUES (2, 'Bob', 300);
-- Something went wrong with Bob's order
ROLLBACK TO SAVEPOINT sp1; -- Undo only Bob's insert
INSERT INTO orders VALUES (3, 'Charlie', 200);
COMMIT; -- Alice and Charlie committed; Bob's insert was rolled back
28. What is a deadlock? How is it detected and prevented?
A deadlock occurs when two or more transactions each hold a lock the other needs, forming a circular wait.
T1 holds Lock(A), waits for Lock(B)
T2 holds Lock(B), waits for Lock(A)
→ Neither can proceed
Detection:
- DBMS maintains a wait-for graph (WFG). A cycle in the WFG = deadlock.
- The DBMS periodically checks for cycles and picks a victim transaction to abort (usually the one with least work done).
Prevention strategies:
| Strategy | How it works |
|---|---|
| Wait-Die | Older transaction waits; younger is killed (dies) |
| Wound-Wait | Older wounds (kills) younger; younger waits for older |
| Lock ordering | Always acquire locks in a fixed global order |
| Timeout | Abort transaction if it waits longer than a threshold |
| Two-phase locking (strict 2PL) | Prevents certain deadlock patterns by holding locks till COMMIT |
Concurrency Control
29. What is two-phase locking (2PL)?
Two-phase locking is a concurrency control protocol that ensures serializability.
Two phases:
- Growing phase: transaction acquires locks but does not release any.
- Shrinking phase: transaction releases locks but does not acquire any.
Variants:
| Variant | Description | Deadlock-free? |
|---|---|---|
| Basic 2PL | Growing + shrinking phases | No |
| Strict 2PL | All exclusive locks held until COMMIT/ROLLBACK | No (but prevents cascading rollbacks) |
| Rigorous 2PL | All locks (shared + exclusive) held until COMMIT | No (but simplest for recovery) |
| Conservative 2PL | Acquire all locks before transaction starts | Yes (but impractical) |
30. What are shared (S) and exclusive (X) locks?
| Lock type | Symbol | Allows others to... | Used for |
|---|---|---|---|
| Shared (S) | S | Read (S lock OK); not write (X lock blocked) | Reading data |
| Exclusive (X) | X | Neither read nor write (all locks blocked) | Writing data |
Lock compatibility matrix:
| Held \ Requested | S | X |
|---|---|---|
| S | ✅ Compatible | ❌ Conflict |
| X | ❌ Conflict | ❌ Conflict |
Intention locks (used in hierarchical locking for large databases):
IS(Intention Shared): intent to place S lock on a descendant node.IX(Intention Exclusive): intent to place X lock on a descendant node.SIX(Shared Intention Exclusive): S lock on current node + intent to X lock descendants.
31. What is MVCC (Multi-Version Concurrency Control)?
MVCC keeps multiple versions of data to allow readers and writers to operate concurrently without blocking each other.
- Readers don't block writers and writers don't block readers.
- Each transaction sees a consistent snapshot of the database as of its start time.
- Old row versions are kept until no active transaction needs them (then garbage-collected).
Used by: PostgreSQL, MySQL InnoDB, Oracle, SQL Server (Snapshot Isolation).
T1 starts at time 10, reads row X → sees version at T=10
T2 starts at time 12, updates row X → creates new version at T=12
T1 still reads the T=10 version (its snapshot) — no lock needed
32. What is timestamp-based concurrency control?
Each transaction gets a unique timestamp when it starts. Data items also have timestamps:
read_TS(X): largest timestamp of any transaction that read X.write_TS(X): largest timestamp of any transaction that wrote X.
Thomas's write rule:
| Operation | Condition to allow | Action if violated |
|---|---|---|
T reads X |
TS(T) ≥ write_TS(X) |
Abort T (T is reading a value overwritten by a newer transaction) |
T writes X |
TS(T) ≥ read_TS(X) AND TS(T) ≥ write_TS(X) |
Abort T or ignore write (Thomas rule) |
Indexing
33. What is an index? What are the types of indexes?
An index is a data structure that speeds up data retrieval by providing a fast path to rows, at the cost of additional storage and slower writes.
Types:
| Index type | Description | Best for |
|---|---|---|
| Clustered | Data rows physically ordered by index key; one per table | Range queries on PK |
| Non-clustered | Separate structure with pointers to data rows; many per table | Lookups on non-PK columns |
| Composite | Index on multiple columns | Multi-column WHERE clauses |
| Covering | Includes all columns needed by a query (avoids row lookup) | Frequent specific queries |
| Unique | Enforces uniqueness + speeds lookup | Email, username columns |
| Full-text | Inverted index for text search | LIKE '%...%' replacement |
| Partial | Index on a subset of rows (with WHERE clause) | Active records only |
| Bitmap | Bit array for each value; very compact | Low-cardinality columns in OLAP |
| Hash | Hash table structure; O(1) equality lookup | Exact-match lookups only |
34. What is a B-tree index? How does it work?
A B-tree (Balanced Tree) is the most common index structure in RDBMS.
Properties:
- All leaf nodes are at the same depth → guaranteed
O(log n)search, insert, delete. - Leaf nodes are linked → efficient range scans.
- Internal nodes store keys and pointers to child nodes.
- Data pages are typically pointed to by leaf nodes (B+ tree variant, used in most RDBMS).
[30 | 60]
/ | \
[10|20] [40|50] [70|80]
B-tree supports:
- Equality:
WHERE id = 42→ O(log n) - Range:
WHERE id BETWEEN 10 AND 50→ O(log n + k) - Order:
ORDER BY id→ traverse leaves - Prefix:
WHERE name LIKE 'Ali%'→ works WHERE name LIKE '%ali%'→ does NOT use B-tree
35. What is the difference between a clustered and non-clustered index?
| Feature | Clustered index | Non-clustered index |
|---|---|---|
| Data storage | Data rows stored in index order | Separate structure; pointers to data rows |
| Per table | Only one | Multiple |
| Read performance | Excellent for range queries | One extra pointer lookup per row |
| Write performance | Slower (must maintain order) | Slightly faster |
| Size | Same as table | Smaller (just keys + pointers) |
| Default in MySQL InnoDB | Primary key = clustered | All other indexes |
File Organization and Storage
36. What are the types of file organization in DBMS?
| Organization | How data is stored | Best access pattern |
|---|---|---|
| Heap (unordered) | Records inserted wherever space exists | Sequential scan; no index |
| Sequential (ordered) | Records sorted by a search key | Range queries; binary search |
| Hashed | Records placed via hash function on search key | Exact-match lookups |
| Clustered (indexed sequential) | Sorted file with index on top (ISAM, B+ tree) | Range + exact-match |
| Direct | Fixed-location access via record ID | Random access by RID |
37. What is a buffer pool/buffer manager?
The buffer pool (buffer cache) is a region of main memory that the DBMS uses to cache disk pages. Reading from disk is ~1,000× slower than reading from RAM.
Buffer manager responsibilities:
- Keep frequently used pages in memory.
- Implement a page replacement policy (LRU, Clock, MRU) when buffer is full.
- Track which pages are dirty (modified but not yet written to disk).
- Coordinate with the transaction manager (dirty pages must be flushed at COMMIT for durability).
Page replacement policies:
| Policy | Description | Use case |
|---|---|---|
| LRU | Evict least recently used page | General workloads |
| Clock (LRU approximation) | Circular buffer with reference bit | Efficient LRU approximation |
| MRU | Evict most recently used | Sequential scans |
| LFU | Evict least frequently used | Long-term caching |
Advanced Topics
38. What is the CAP theorem?
The CAP theorem (Brewer's theorem) states that a distributed data store can guarantee at most two of the following three properties simultaneously:
| Property | Meaning |
|---|---|
| Consistency (C) | Every read receives the most recent write or an error |
| Availability (A) | Every request receives a response (not necessarily the latest data) |
| Partition tolerance (P) | System continues operating even if network partitions occur |
Since network partitions are unavoidable in distributed systems, you must choose between CP or AP:
| Choice | Behaviour during partition | Examples |
|---|---|---|
| CP | Returns error rather than stale data | HBase, ZooKeeper, MongoDB (strong consistency mode) |
| AP | Returns possibly stale data rather than error | Cassandra, CouchDB, DynamoDB |
| CA (single node) | Not partition-tolerant — not a distributed system | Traditional RDBMS (single-node) |
39. What is the difference between OLTP and OLAP?
| Feature | OLTP | OLAP |
|---|---|---|
| Purpose | Day-to-day transactional operations | Analytical reporting, BI |
| Query type | Simple INSERT/UPDATE/DELETE + lookups | Complex aggregations over large datasets |
| Data currency | Real-time | Historical (hours to days old) |
| Data volume | GB–TB | TB–PB |
| Normalisation | Highly normalised (3NF) | Denormalised (star/snowflake schema) |
| Concurrent users | Thousands | Dozens to hundreds |
| Response time | Milliseconds | Seconds to minutes |
| Examples | MySQL, PostgreSQL, Oracle | Snowflake, BigQuery, Redshift, ClickHouse |
40. What are stored procedures and triggers?
Stored procedure: a pre-compiled named program stored in the database and executed on demand.
CREATE PROCEDURE TransferFunds(
IN from_account INT, IN to_account INT, IN amount DECIMAL(10,2)
)
BEGIN
UPDATE accounts SET balance = balance - amount WHERE id = from_account;
UPDATE accounts SET balance = balance + amount WHERE id = to_account;
END;
CALL TransferFunds(1, 2, 500.00);
Trigger: a procedure that executes automatically in response to a DML event on a table.
CREATE TRIGGER audit_salary_change
AFTER UPDATE ON Employee
FOR EACH ROW
BEGIN
IF OLD.salary <> NEW.salary THEN
INSERT INTO SalaryAudit(emp_id, old_salary, new_salary, changed_at)
VALUES (NEW.id, OLD.salary, NEW.salary, NOW());
END IF;
END;
| Feature | Stored procedure | Trigger |
|---|---|---|
| Invocation | Explicit (CALL) | Automatic (on event) |
| Parameters | Yes | No (uses OLD/NEW) |
| Can be called from app | Yes | No |
| Events | Any | INSERT, UPDATE, DELETE |
| Timing | N/A | BEFORE or AFTER event |
41. What is relational algebra?
Relational algebra is a procedural query language that forms the theoretical foundation of SQL. It operates on relations (tables) and returns relations.
Core operations:
| Operation | Symbol | SQL equivalent | Description |
|---|---|---|---|
| Selection | σ (sigma) | WHERE |
Filter rows matching a condition |
| Projection | π (pi) | SELECT col |
Select specific columns |
| Union | ∪ | UNION |
Rows in either relation (no duplicates) |
| Set difference | − | EXCEPT |
Rows in R1 but not R2 |
| Cartesian product | × | CROSS JOIN |
All combinations of rows |
| Rename | ρ (rho) | AS |
Rename a relation or attribute |
| Natural join | ⋈ | NATURAL JOIN |
Join on common attributes |
| Left outer join | ⟕ | LEFT JOIN |
All rows from left + matching from right |
| Division | ÷ | (complex SQL) | Find tuples in R1 related to ALL tuples in R2 |
Example:
Find names of students enrolled in course C101:
π(name) ( σ(course_id='C101') (Student ⋈ Enrollment) )
42. What is a cursor in DBMS?
A cursor is a database object that allows row-by-row processing of a result set — like an iterator over query results.
DECLARE student_cursor CURSOR FOR
SELECT id, name FROM Student WHERE status = 'active';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN student_cursor;
read_loop: LOOP
FETCH student_cursor INTO v_id, v_name;
IF done THEN LEAVE read_loop; END IF;
-- process each row
END LOOP;
CLOSE student_cursor;
Types:
| Type | Description |
|---|---|
| Implicit | Automatically created by DML statements |
| Explicit | Declared by programmer for row-by-row processing |
| Forward-only | Can only move forward through results |
| Scrollable | Can move forward, backward, or jump to a position |
| Static | Works on a snapshot of data |
| Dynamic | Reflects changes made to data while cursor is open |
43. What is hashing in DBMS? Types of hashing?
Hashing applies a hash function to a key to determine which storage bucket a record belongs to, enabling O(1) average-case access.
Types:
| Type | Description | Problem |
|---|---|---|
| Static hashing | Fixed number of buckets | Overflow when data grows; reorganisation needed |
| Dynamic (extendible) hashing | Directory doubles as needed | More complex |
| Linear hashing | Splits buckets one at a time | Gradual growth |
Collision handling:
- Chaining (open hashing): overflow records stored in a linked list attached to the bucket.
- Open addressing (closed hashing): probe next available bucket (linear probing, quadratic probing, double hashing).
44. What is query processing and query optimisation?
Query processing steps:
SQL query → Parser → Relational algebra expression
→ Query optimiser → Execution plan (most efficient)
→ Query executor → Result
Query optimiser tasks:
- Parsing and validation: check syntax, verify table/column names exist.
- Logical optimisation: rewrite algebraic expression (push selections down, remove redundancy).
- Physical planning: choose access methods (index vs full scan), join algorithms.
- Cost estimation: estimate I/O, CPU cost using statistics (row counts, column histograms).
Common join algorithms:
| Algorithm | When used | Cost |
|---|---|---|
| Nested loop join | Small outer table or inner table has index | O(n × m) |
| Block nested loop | Larger tables, no index | O(n × m / B) blocks |
| Sort-merge join | Both inputs sorted on join key | O(n log n + m log m) |
| Hash join | Equi-join, no useful index, fits in memory | O(n + m) |
45. What is the difference between a primary index and a secondary index?
| Feature | Primary (clustered) index | Secondary (non-clustered) index |
|---|---|---|
| Built on | Ordering key field (usually PK) | Any non-ordering field |
| Data order | Data file is physically sorted by index key | Data file not sorted by this field |
| Per table | One | Many |
| Lookup cost | Direct access | Extra pointer lookup (one more I/O) |
| Dense/sparse | Can be sparse (one entry per block) | Must be dense (one entry per record) |
Practical and Scenario Questions
46. How would you design a database schema for a university system?
Entities and relationships:
Student(student_id PK, name, dob, email, enrollment_year)
Faculty(faculty_id PK, name, department_id FK, email, hire_date)
Department(dept_id PK, name, building, head_faculty_id FK)
Course(course_id PK, title, credits, dept_id FK)
Section(section_id PK, course_id FK, faculty_id FK, semester, year, room)
Enrollment(student_id FK, section_id FK, grade, enrollment_date)
PK(student_id, section_id)
Prerequisite(course_id FK, prereq_id FK)
PK(course_id, prereq_id)
Key design decisions:
Enrollmentis the M:N resolution table betweenStudentandSection.Prerequisiteis a recursive relationship onCourse.Department.head_faculty_idis nullable (department may not have a head yet).- Separate
SectionfromCourseto model the same course taught multiple times per semester.
47. What is the difference between a relation and a table?
| Aspect | Relation (mathematical) | Table (physical) |
|---|---|---|
| Duplicate rows | Not allowed (set theory) | Allowed (unless DISTINCT or PK) |
| Row order | No order | Physical order may exist |
| Column order | No order | Order matters (for positional INSERT) |
| Domain | Strictly typed | Types enforced by DBMS |
| Naming | Formally defined | May have informal names |
In SQL, tables are multisets (bags), not true sets — they allow duplicate rows unless constrained.
48. What is the difference between a natural join and an equi-join?
| Feature | Natural join | Equi-join |
|---|---|---|
| Join condition | Automatically joins on ALL columns with the same name | Explicit ON col1 = col2 |
| Result columns | Duplicate join columns removed | Duplicate columns kept |
| Ambiguity risk | High (joins on any column name match) | Low (explicit) |
| Recommendation | Avoid in production SQL | Preferred |
-- Equi-join (preferred)
SELECT e.name, d.dept_name
FROM Employee e
JOIN Department d ON e.dept_id = d.dept_id;
-- Natural join (risky — joins on ALL matching column names)
SELECT name, dept_name FROM Employee NATURAL JOIN Department;
49. Explain the concept of a lossless decomposition.
A decomposition of relation R into R1 and R2 is lossless if the original relation can be perfectly reconstructed by joining R1 and R2 — no spurious (extra) tuples are introduced.
Test (Lossless-Join Property):
A decomposition {R1, R2} is lossless if at least one of these functional dependencies holds:
R1 ∩ R2 → R1 − R2(intersection is a super key of R1), orR1 ∩ R2 → R2 − R1(intersection is a super key of R2)
Example:
R(A, B, C) with FD: A → B
Decompose into R1(A, B) and R2(A, C)
R1 ∩ R2 = {A}
A → B means A is a super key of R1(A, B) ✅ → Lossless
A lossy decomposition introduces extra rows when joined and loses information — always a design error.
50. What is the difference between SQL and NoSQL databases?
| Feature | SQL (Relational) | NoSQL |
|---|---|---|
| Data model | Tables (rows + columns) | Document, key-value, column-family, graph |
| Schema | Fixed schema (DDL required) | Flexible / schema-less |
| ACID | Full ACID by default | Usually BASE (Basically Available, Soft state, Eventually consistent) |
| Joins | Native, powerful | Limited or no joins |
| Scalability | Vertical (scale up) + limited horizontal | Horizontal (scale out) designed in |
| Query language | SQL (standard) | Varies per system (MQL, CQL, Gremlin…) |
| Consistency | Strong by default | Eventual consistency common |
| Best for | Structured data, complex queries, transactions | High-volume, flexible schemas, distributed scale |
| Examples | PostgreSQL, MySQL, Oracle, SQL Server | MongoDB, Cassandra, Redis, DynamoDB, Neo4j |
Common mistakes
| Mistake | Problem | Fix |
|---|---|---|
| Confusing 2NF and 3NF | 2NF removes partial dependencies; 3NF removes transitive | Remember: 2NF = whole key, 3NF = nothing but key |
| Saying "TRUNCATE is DML" | TRUNCATE is DDL (implicit commit, not rollback-able in most RDBMS) | Memorise: DELETE=DML, TRUNCATE=DDL |
| Ignoring NULL in joins | NULLs don't match in INNER JOIN | Use OUTER JOIN or IS NULL check |
| Confusing clustered and primary index | They're related but not identical | Clustered = physical ordering; primary key just enforces uniqueness |
| Mixing up deadlock prevention vs detection | Prevention avoids deadlock; detection finds + resolves it | Timeout = simple prevention; WFG = detection |
| Saying CAP means "pick any two freely" | Partition tolerance is mandatory in distributed systems | Real choice is C vs A when partition occurs |
| Treating all views as updatable | Views with aggregation/GROUP BY/UNION are not updatable | Check your RDBMS documentation |
| Not understanding MVCC | Think locks are the only concurrency mechanism | PostgreSQL and MySQL InnoDB default to MVCC |
DBMS vs related topics
| Topic | Focus | Key content |
|---|---|---|
| DBMS | Theory + design | ER diagrams, normalisation, ACID, concurrency control, relational algebra |
| SQL | Query language | SELECT, JOIN, aggregate, subquery, window functions |
| Database design | Applied | Schema design, indexing strategy, partitioning, denormalisation |
| Data warehousing | OLAP | Star/snowflake schema, ETL, facts, dimensions |
| Distributed databases | Scale | CAP, replication, sharding, consensus |
| NoSQL | Alternatives | Document/key-value/column/graph models, BASE, eventual consistency |
FAQ
Q: Is DBMS the same as SQL?
No. DBMS is the system (software like MySQL or PostgreSQL). SQL is the query language used to interact with a relational DBMS. You can have a DBMS without SQL (e.g., MongoDB uses MQL).
Q: What is the most important normal form to know for interviews?
Know 1NF through BCNF thoroughly — especially 2NF (no partial dependency) and 3NF (no transitive dependency). BCNF is often asked in theory questions. 4NF and 5NF are bonus points.
Q: What's the difference between ACID and BASE?
ACID (Atomicity, Consistency, Isolation, Durability) is used by traditional RDBMS for strong consistency. BASE (Basically Available, Soft state, Eventual consistency) is used by many NoSQL systems that trade consistency for availability and scalability.
Q: How is a DBMS different from a file system?
A file system just stores and retrieves files. A DBMS adds: structured query support, data integrity enforcement, concurrent access control, transaction management, recovery mechanisms, and security controls.
Q: What is the difference between a schema and a database?
A database is the entire container (all data + structures). A schema is the logical blueprint describing the structure (tables, columns, constraints, relationships) — like the floor plan of a building vs the building itself. In some RDBMS (PostgreSQL), a schema is also a namespace within a database.
Q: Why study DBMS theory if I just use SQL day-to-day?
DBMS theory explains why SQL works the way it does — why JOINs behave as they do, what query optimisers are doing, why transactions prevent data corruption, and when to use indexes. It helps you debug strange behaviour, design schemas correctly, and reason about performance.