IIT Madras Zanzibar · Teaching

← Course Overview

Question Bank

Organised by module and difficulty. Use this bank to prepare for Quiz 1, Quiz 2, and the end-semester examination. Questions are not a substitute for lab exercises and the semester project.

Reference Sheet: Pair these problems with the compiled 2-page PDF formula summary before inspecting solutions.SQL & Normalization Cheat Sheet (PDF)
Module 01

ER Model & Foundations


Q1EasyQuiz

What is the difference between a strong entity and a weak entity in an ER diagram? Give one example of each.

Reveal Worked Solution
A strong entity has its own independent primary key (for example, Student(StudentID)), whereas a weak entity lacks a sufficient key of its own and depends on an identifying owner entity via a partial key and total participation (for example, OrderItem(LineNo) owned by Orders(OrderID)).
Q2EasyQuiz

List the three types of attributes in an ER model and give an example of each.

Reveal Worked Solution
Three attribute types: (1) Simple vs. composite (GPA vs. FullName(First, Last)); (2) Single-valued vs. multi-valued (BirthDate vs. PhoneNumbers); (3) Stored vs. derived (BirthDate vs. Age).
Q3EasyICA

What is the purpose of a DBMS? Name two advantages of using a DBMS over flat-file storage.

Reveal Worked Solution
A DBMS provides structured persistence, concurrency control, crash recovery, and declarative querying. Compared with flat files, it prevents data redundancy/inconsistency and enforces integrity constraints and multi-user ACID isolation automatically.
Q4EasyQuiz

Define cardinality ratio in an ER relationship. What are the four possible cardinality ratios?

Reveal Worked Solution
Cardinality ratio specifies the maximum number of relationship instances an entity can participate in. The four binary ratios are 1:1, 1:N, N:1, and M:N.
Q1IntermediateQuiz

Draw an ER diagram for a university database with entities Student, Course, and Instructor. Include appropriate attributes, primary keys, and relationships with cardinality constraints.

Reveal Worked Solution
Entities: Student(StudentID, Name, Major), Course(CourseID, Title, Credits), Instructor(InstID, Name, Dept). Relationships: Enrolls(M:N) between Student and Course with attribute Grade; Teaches(1:N) from Instructor to Course.
Q2IntermediateQuiz

A library system has Books, Members, and Loans. A member can borrow many books; a book can be borrowed many times by different members. Model this with an ER diagram including participation constraints and the Loan as an associative entity with date attributes.

Reveal Worked Solution
Model Book(ISBN, Title) and Member(MemberID, Name) linked by associative entity Loan(LoanID, CheckoutDate, DueDate, ReturnDate) with total 1:N participation from Loan to both Book and Member.
Q3IntermediateICA

Explain the difference between total and partial participation. In your university ER diagram, which relationships have total participation? Justify each choice.

Reveal Worked Solution
Total participation requires every entity in the set to join at least one relationship instance (double line), whereas partial participation allows unmatched entities (single line). In a university schema, every Course section has total participation in Teaches, whereas an Instructor on sabbatical may have partial participation.
Q1AdvancedExam

Design a complete ER diagram for a hospital management system supporting patients, doctors, wards, appointments, prescriptions, and billing. Discuss every design decision including specialisation/generalisation hierarchies, weak entities, and cardinality constraints. Identify any design ambiguities and how you resolved them.

Reveal Worked Solution
Model Patient, Doctor (ISA specialization from Staff), Ward, Appointment, Prescription, and weak entity InvoiceLine owned by Bill. Resolve temporal ambiguities by storing Appointment(ApptID, DateTime) and separating billing line items from clinical prescriptions with strict foreign keys.
Q2AdvancedProject

Convert the Extended ER (EER) concept of specialisation into a relational schema. Discuss the three conversion strategies (single table, table per subclass, table per concrete class) and analyse when each is appropriate in terms of query performance and data integrity.

Reveal Worked Solution
(1) Single table with nullable subclass columns and a type discriminator (fast queries, wastes space on NULLs); (2) Superclass table plus subclass tables joined on PK/FK (normalized, avoids NULLs, needs joins); (3) Concrete subclass tables repeating inherited attributes (fast concrete scans, complicates superclass-wide queries).
Module 02

Relational Model


Q1EasyQuiz

Define: relation, tuple, attribute, domain, degree, and cardinality. Use a concrete example for each.

Reveal Worked Solution
Relation: named table (Student); Tuple: single row; Attribute: named column (GPA); Domain: allowed atomic values (real numbers in 0.0..4.0); Degree: number of columns; Cardinality: current number of rows.
Q2EasyICA

What is the difference between a primary key, a candidate key, and a foreign key? Give an example of each in a Student-Enrollment schema.

Reveal Worked Solution
Candidate key: minimal unique row identifier (StudentID, Email); Primary key: chosen candidate key (StudentID); Foreign key: column referencing a primary/unique key in another table (Enrollment.StudentID referencing Student.StudentID).
Q3EasyQuiz

State the entity integrity constraint and the referential integrity constraint. What happens if either is violated?

Reveal Worked Solution
Entity integrity forbids NULL values inside any primary key attribute. Referential integrity requires every non-null foreign key value to match an existing parent primary key value; violating either rejects the write.
Q1IntermediateQuiz

Convert the following ER diagram components into a relational schema: a many-to-many relationship between Employee(EmpID, Name) and Project(ProjID, Title) with a WorksOn relationship carrying a Hours attribute.

Reveal Worked Solution
Create Employee(EmpID, Name), Project(ProjID, Title), and junction table WorksOn(EmpID, ProjID, Hours) where EmpID and ProjID form a composite primary key and act as foreign keys.
Q2IntermediateICA

A weak entity OrderItem depends on Order. How do you represent this in a relational schema? What is the primary key of OrderItem?

Reveal Worked Solution
Include parent primary key OrderID inside OrderItem as a foreign key with ON DELETE CASCADE. The primary key of OrderItem is the composite (OrderID, ItemNo).
Q1AdvancedExam

Discuss the three referential integrity violation response options: RESTRICT, CASCADE, and SET NULL. For each, give a real-world scenario where it is the most appropriate choice. What are the risks if the wrong option is chosen?

Reveal Worked Solution
RESTRICT blocks parent deletion if children exist (protecting financial invoices); CASCADE deletes dependent child rows automatically (removing weak OrderItem rows when an order cancels); SET NULL keeps child records unlinked (keeping resolved support tickets if a technician leaves).
Module 03

Relational Algebra


Q1EasyQuiz

Name the six core relational algebra operations and briefly describe what each does.

Reveal Worked Solution
Selection (sigma: filter rows), Projection (pi: choose columns), Union (U: combine rows), Set Difference (-: rows in A not B), Cartesian Product (x: all pairs), and Rename (rho: alias relation/attributes).
Q2EasyICA

Given relation Student(ID, Name, GPA, DeptID), write a relational algebra expression to retrieve the names of all students with GPA > 3.5.

Reveal Worked Solution
pi_Name(sigma_{GPA > 3.5}(Student)).
Q3EasyQuiz

What is the difference between a natural join and an equi-join? Give an example where the result differs.

Reveal Worked Solution
Equi-join keeps both identical join columns from R and S (requiring R.DeptID = S.DeptID), whereas Natural Join joins on all shared column names and keeps only one copy of each shared column.
Q1IntermediateQuiz

Given Employee(EmpID, Name, DeptID, Salary) and Department(DeptID, DeptName, ManagerID), write relational algebra expressions for: (a) names of employees in the "CS" department, (b) names of managers, (c) departments with no employees.

Reveal Worked Solution
(a) pi_Name(Employee |x| sigma_{DeptName='CS'}(Department)); (b) pi_{e.Name}(rho_e(Employee) |x|_{e.EmpID=d.ManagerID} Department); (c) pi_DeptID(Department) - pi_DeptID(Employee).
Q2IntermediateICA

Explain the division operator in relational algebra. Use it to find students who have enrolled in ALL courses offered by the CS department.

Reveal Worked Solution
Division R / S returns A-values in R(A, B) paired with every B-value in S(B). Expression: pi_{StudentID, CourseID}(Enroll) / pi_{CourseID}(sigma_{Dept='CS'}(Course)).
Q3IntermediateQuiz

Show that the intersection operation (∩) is not a basic operation: express it using only union and set difference.

Reveal Worked Solution
R intersect S = R - (R - S). Removing rows in R that are absent from S leaves only rows present in both.
Q1AdvancedExam

Relational algebra expressions are not unique for a given query. Write three different relational algebra expressions for "find names of employees who earn more than their manager." Then explain how a query optimizer uses equivalence rules to transform one expression into a more efficient one.

Reveal Worked Solution
Push selections before joins or reorder joins via associativity: e.g. join Employee with Department on ManagerID, project manager salary, then filter e.Salary > m.Salary. Cost-based optimizers apply equivalence rules such as selection pushdown and projection pruning to shrink intermediate cardinalities early.
Q2AdvancedExam

Extended relational algebra includes outer joins and aggregation. Express the following using extended RA: "For each department, list the department name and the average salary of its employees. Include departments with no employees, showing NULL for their average."

Reveal Worked Solution
gamma_{DeptName, AVG(Salary)}(Department LEFT OUTER JOIN Employee) (grouping by DeptName preserves empty departments with NULL average salary).
Module 04

SQL Foundations


Q1EasyICA

Write SQL to create a table Product(ProductID INT PRIMARY KEY, Name VARCHAR(100), Price DECIMAL(10,2), Stock INT NOT NULL). Then insert three rows and retrieve all rows where Price > 50.

Reveal Worked Solution
CREATE TABLE Product (ProductID INT PRIMARY KEY, Name VARCHAR(100), Price DECIMAL(10,2), Stock INT NOT NULL); then INSERT INTO Product VALUES ... and SELECT * FROM Product WHERE Price > 50;.
Q2EasyQuiz

What is the difference between WHERE and HAVING? When must you use each?

Reveal Worked Solution
WHERE filters individual rows before grouping (and cannot reference aggregate functions), whereas HAVING filters aggregated groups after GROUP BY.
Q3EasyICA

Explain the difference between DELETE, TRUNCATE, and DROP. Which is reversible and which is not?

Reveal Worked Solution
DELETE removes selected rows via logged DML and can roll back inside a transaction; TRUNCATE deallocates all table pages rapidly; DROP removes both table data and its schema definition permanently.
Q4EasyQuiz

Write SQL to retrieve all students whose names start with "A" and sort them alphabetically. Use the Student(ID, Name, GPA) schema.

Reveal Worked Solution
SELECT * FROM Student WHERE Name LIKE 'A%' ORDER BY Name ASC;.
Q1IntermediateQuiz

Write SQL for all four join types (INNER, LEFT OUTER, RIGHT OUTER, FULL OUTER) on Employee(EmpID, Name, DeptID) and Department(DeptID, DeptName). Describe what rows appear in each result that would not appear in the others.

Reveal Worked Solution
INNER JOIN keeps matching DeptID pairs; LEFT OUTER preserves employees with NULL DeptID; RIGHT OUTER preserves empty departments; FULL OUTER preserves unmatched rows from both sides.
Q2IntermediateICA

Use the NULL semantics of SQL to explain: why does NULL = NULL evaluate to UNKNOWN? How does this affect a WHERE clause that filters on a nullable column?

Reveal Worked Solution
NULL denotes missing/unknown data, so comparing two unknown values yields UNKNOWN. Because WHERE keeps only rows evaluating to TRUE, use IS NULL rather than = NULL.
Q1AdvancedExam

A query returns unexpected NULL values after an outer join. Walk through the three-valued logic (TRUE, FALSE, UNKNOWN) to explain why a WHERE dept = 'CS' clause silently drops outer-join NULLs. Rewrite the query to correctly preserve them.

Reveal Worked Solution
Applying WHERE d.dept = 'CS' after a LEFT JOIN turns outer-joined NULL rows into UNKNOWN and discards them, turning the query into an inner join. Move the predicate into the ON clause (LEFT JOIN Dept d ON e.dept_id = d.id AND d.dept = 'CS').
Module 05

SQL Intermediate


Q1EasyICA

Given Orders(OrderID, CustomerID, Amount, OrderDate), write SQL to find the total amount ordered per customer, showing only customers whose total exceeds 1000.

Reveal Worked Solution
SELECT CustomerID, SUM(Amount) AS total_amt FROM Orders GROUP BY CustomerID HAVING SUM(Amount) > 1000;.
Q2EasyQuiz

What does a correlated subquery do? Give a simple example and explain why it can be slower than a join.

Reveal Worked Solution
A correlated subquery references columns from the outer row and executes conceptually once per outer row, whereas a hash or merge join evaluates the relationship in a single pass.
Q1IntermediateQuiz

Write SQL using EXISTS to find all customers who have placed at least one order in the last 30 days. Then rewrite the same query using a JOIN. Which form does the query optimizer prefer and why?

Reveal Worked Solution
SELECT c.* FROM Customer c WHERE EXISTS (SELECT 1 FROM Orders o WHERE o.CustomerID = c.CustomerID AND o.OrderDate >= CURRENT_DATE - INTERVAL '30 days');. A semi-join via EXISTS stops scanning on the first match and avoids duplicate customer rows.
Q2IntermediateICA

Using Employee(EmpID, Name, Salary, DeptID), write SQL to find the second-highest salary in each department. Solve it two ways: once with a subquery and once with DENSE_RANK().

Reveal Worked Solution
Window form: WITH ranked AS (SELECT *, DENSE_RANK() OVER (PARTITION BY DeptID ORDER BY Salary DESC) AS rk FROM Employee) SELECT * FROM ranked WHERE rk = 2;. Subquery form: filter Salary = (SELECT MAX(Salary) FROM Employee e2 WHERE e2.DeptID = e1.DeptID AND e2.Salary < (SELECT MAX(Salary) FROM Employee e3 WHERE e3.DeptID = e1.DeptID)).
Q3IntermediateQuiz 2

Explain the difference between IN, EXISTS, and ANY/ALL in SQL subqueries. For each, write an example query and state when it is preferred over the others.

Reveal Worked Solution
IN tests set membership (beware NULLs with NOT IN); EXISTS performs short-circuit semi-joins safely with NULLs; ANY/ALL compares a scalar against a subquery column vector (for example, > ALL(...)).
Q1AdvancedExam

A manager asks: "Find all employees who earn more than the average salary of their own department." Write this as (a) a correlated subquery, (b) a derived table, and (c) a window function. Compare the readability and likely query plan cost of each approach.

Reveal Worked Solution
(a) Correlated: WHERE e.Salary > (SELECT AVG(Salary) FROM Employee d WHERE d.DeptID = e.DeptID); (b) Derived table: join Employee with (SELECT DeptID, AVG(Salary) avg_s FROM Employee GROUP BY DeptID); (c) Window: compute AVG(Salary) OVER (PARTITION BY DeptID) in a single scan without self-joining.
Module 06

SQL Advanced


Q1EasyICA

What is a Common Table Expression (CTE)? Write a CTE that computes total sales per region and then selects only regions with total sales above the average.

Reveal Worked Solution
A CTE names a temporary query block inside WITH: WITH reg AS (SELECT region, SUM(amount) total FROM Sales GROUP BY region) SELECT * FROM reg WHERE total > (SELECT AVG(total) FROM reg);.
Q2EasyQuiz 2

What is the difference between a stored procedure and a trigger in SQL? Give a real-world example where each is appropriate.

Reveal Worked Solution
A stored procedure is invoked explicitly by an application (for example, monthly payroll settlement), whereas a trigger fires automatically on DML events (for example, recording every balance edit in an audit table).
Q1IntermediateQuiz 2

Using SalesTransaction(TxnID, SaleDate, Amount, SalespersonID), write SQL with window functions to compute: (a) running total of Amount per salesperson ordered by date, (b) each transaction's rank within its month, (c) the 3-transaction moving average for each salesperson.

Reveal Worked Solution
(a) SUM(Amount) OVER (PARTITION BY SalespersonID ORDER BY SaleDate, TxnID); (b) RANK() OVER (PARTITION BY strftime('%Y-%m', SaleDate) ORDER BY Amount DESC); (c) AVG(Amount) OVER (PARTITION BY SalespersonID ORDER BY SaleDate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW).
Q2IntermediateICA

Write a recursive CTE to list all ancestors of a given employee in an Employee(EmpID, Name, ManagerID) hierarchy table.

Reveal Worked Solution
WITH RECURSIVE Ancestors AS (SELECT EmpID, Name, ManagerID FROM Employee WHERE EmpID = :id UNION ALL SELECT e.EmpID, e.Name, e.ManagerID FROM Employee e JOIN Ancestors a ON e.EmpID = a.ManagerID) SELECT * FROM Ancestors;.
Q1AdvancedExam

Design a trigger-based audit system for a banking Account(AccountID, Balance) table. The trigger must log every UPDATE to a separate AuditLog table recording the old and new balance, the timestamp, and the database user. Discuss the performance implications of row-level versus statement-level triggers for high-throughput systems.

Reveal Worked Solution
Use an AFTER UPDATE ON Account FOR EACH ROW trigger inserting (OLD.AccountID, OLD.Balance, NEW.Balance, CURRENT_TIMESTAMP, CURRENT_USER) into AuditLog. Row-level triggers execute once per modified row (higher per-row overhead on bulk loads), whereas statement-level triggers fire once per SQL statement using transition tables.
Module 07

Normalization


Q1EasyQuiz 2

Define functional dependency. Give two examples from a university database and identify which is trivial and which is non-trivial.

Reveal Worked Solution
An FD X -> Y states that identical X values determine identical Y values. Trivial: (StudentID, Name) -> StudentID (RHS subset of LHS); Non-trivial: StudentID -> Name.
Q2EasyICA

What anomalies (insertion, update, deletion) can occur in an unnormalized relation? Give a concrete example of each using a StudentCourse(StudentID, StudentName, CourseID, CourseName, Grade) table.

Reveal Worked Solution
Insertion anomaly (cannot add a new course with zero enrolled students); Update anomaly (changing a student name requires updating every course row); Deletion anomaly (dropping the last student in a course deletes the course title).
Q3EasyQuiz 2

State the conditions for 1NF, 2NF, 3NF, and BCNF. For each, give a relation that satisfies it but violates the next higher normal form.

Reveal Worked Solution
1NF: atomic values only; 2NF: no partial dependency on part of a candidate key; 3NF: no transitive dependency of non-prime attributes; BCNF: every non-trivial FD determinant is a superkey. Example: R(A,B,C) with AB->C, C->B is in 3NF (B is prime) but violates BCNF.
Q1IntermediateQuiz 2

Given R(A, B, C, D, E) with FDs: A → B, BC → D, D → E. (a) Find all candidate keys. (b) Identify the highest normal form of R. (c) Decompose R into BCNF and verify the decomposition is lossless.

Reveal Worked Solution
(a) Candidate key is AC (only AC reaches ABCDE: A->B, BC->D, D->E). (b) Highest normal form is 1NF because A -> B is a partial dependency on candidate key AC. (c) Decompose into R1(A, B), R2(B, C, D), R3(D, E), and R4(A, C); joining step-by-step on determinants guarantees lossless reconstruction.
Q2IntermediateExam

Using Armstrong's axioms (reflexivity, augmentation, transitivity), derive all FDs implied by the set {A → B, B → C, C → D}. Compute the closure of {A}.

Reveal Worked Solution
Closure {A}+ = {A, B, C, D} via transitivity (A->B, B->C implies A->C; with C->D implies A->D), plus trivial/augmented subsets.
Q1AdvancedExam

BCNF decomposition is always lossless but may not be dependency-preserving. Construct an example where achieving BCNF loses a functional dependency. Show how 3NF decomposition preserves it. Discuss the trade-off a database designer must make.

Reveal Worked Solution
Take R(City, Street, Zip) with FDs {City, Street} -> Zip and Zip -> City. Decomposing into R1(Zip, City) and R2(Zip, Street) achieves BCNF losslessly, yet loses direct single-table enforcement of {City, Street} -> Zip. 3NF synthesis keeps the original table if preserving every FD without joins matters more than eliminating all redundancy.
Q2AdvancedProject

A denormalized table is sometimes preferred in data warehouses. Explain the concept of a "star schema" and argue why 3NF normalization would harm rather than help query performance in an OLAP setting.

Reveal Worked Solution
An OLAP star schema intentionally keeps denormalized dimension tables around a central fact table to minimize expensive multi-way joins across millions of analytical scan rows, relying on ETL pipelines rather than frequent OLTP row updates.
Module 08

Storage & Indexing


Q1EasyQuiz 2

What is a B+ tree index? How does it differ from a B-tree? Why do database systems prefer B+ trees?

Reveal Worked Solution
A B+ tree stores keys in internal routing nodes and places all data pointers solely in doubly linked leaf nodes, giving higher fanout (shorter height) and sequential leaf scans for range queries compared with a B-tree.
Q2EasyICA

Explain the difference between a clustered index and a non-clustered index. Can a table have more than one clustered index? Why or why not?

Reveal Worked Solution
A clustered index dictates the physical storage order of table rows (only one per table), whereas non-clustered indexes hold separate sorted key-pointer entries (many per table).
Q3EasyQuiz 2

What is the role of the buffer pool in a DBMS? What happens when a page is "dirty" in the buffer pool?

Reveal Worked Solution
The buffer pool caches disk pages in RAM to minimize physical I/O. A dirty page has been modified in RAM and must be flushed (under WAL ordering) before eviction.
Q1IntermediateExam

A B+ tree of order 4 has 10,000 records. Estimate the height of the tree and the number of disk accesses needed for (a) a point query, (b) a range query returning 200 records. Compare this to a heap file scan.

Reveal Worked Solution
An order-4 B+ tree holds 2–3 keys per node (average fanout ~3): height is ceil(log_3(10000/3)) ≈ 8 levels, so point lookup takes ~8 I/Os and a 200-record range scan takes ~8 + 67 ≈ 75 I/Os, versus scanning all ~2,500 heap pages.
Q2IntermediateICA

Explain static hashing and dynamic (extendible) hashing. When does static hashing perform poorly and how does dynamic hashing address it?

Reveal Worked Solution
Static hashing fixes bucket count M and degrades into long overflow chains as records grow. Extendible hashing uses a directory of bucket pointers indexed by d hash bits, doubling only the directory and splitting individual full buckets on overflow.
Q1AdvancedExam

A high-traffic e-commerce site runs queries like: "find all orders by CustomerID placed between two dates sorted by Amount." Design an indexing strategy (which columns, which index type, clustered or not). Justify your choices considering the trade-off between query speed and write overhead.

Reveal Worked Solution
Create a composite B+ tree index on (CustomerID, OrderDate) INCLUDE (Amount) (clustered on (CustomerID, OrderDate) if read-heavy). Equal CustomerID and range OrderDate use a tight range scan while covering Amount avoids heap lookups; balance index count against write-amplification on inserts.
Module 09

Query Processing & Transactions


Q1EasyQuiz 2

State the four ACID properties of a database transaction. Give a banking example that shows what goes wrong if each property is violated.

Reveal Worked Solution
Atomicity (all-or-nothing transfer), Consistency (total funds preserved), Isolation (concurrent transfers do not see partial balances), Durability (committed transfer survives power failure).
Q2EasyICA

What is a schedule in the context of concurrency control? What is the difference between a serial schedule and a serializable schedule?

Reveal Worked Solution
A schedule is an interleaved sequence of operations from concurrent transactions. A serial schedule runs transactions one after another without overlap; a serializable schedule is equivalent in effect to some serial schedule.
Q3EasyQuiz 2

Name three types of read anomalies that can occur without proper isolation. Define each and give an example.

Reveal Worked Solution
Dirty read (reading uncommitted data later rolled back), Non-repeatable read (re-reading a row sees committed edits), and Phantom read (re-running a range predicate sees newly inserted rows).
Q1IntermediateExam

Two transactions T1 and T2 both read then update the same account balance. Draw a schedule that results in a lost update. Then show how Two-Phase Locking (2PL) prevents this and what deadlock scenario might arise as a side effect.

Reveal Worked Solution
Lost update: T1:R(A), T2:R(A), T1:W(A), T2:W(A) overwrites T1's edit. Strict 2PL requires an exclusive lock before writing (or shared-to-exclusive upgrade), blocking conflicting writes; deadlocks arise if T1 and T2 both hold S-locks and wait to upgrade to X-locks.
Q2IntermediateICA

Explain the four SQL isolation levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE. For each level, state which anomalies it allows and give a use case where that level is appropriate.

Reveal Worked Solution
READ UNCOMMITTED allows dirty/non-repeatable/phantom reads; READ COMMITTED blocks dirty reads; REPEATABLE READ blocks dirty and non-repeatable reads; SERIALIZABLE prevents all three (plus write skew).
Q1AdvancedExam

Explain the ARIES recovery algorithm (Analysis, Redo, Undo phases). Given a log with COMMIT for T1 but no COMMIT for T2 at crash time, walk through each phase. Why does ARIES use a "no-force, steal" buffer management policy and what does it imply for the log?

Reveal Worked Solution
Analysis scans forward from the last checkpoint to find dirty pages and active loser transactions (T2); Redo repeats all logged updates forward from minimum recLSN; Undo rolls back loser T2 backwards writing CLRs while leaving committed T1 durable. Steal/No-Force maximizes buffer performance and mandates both Undo and Redo log records.
Module 10

Modern & AI Data Systems


Q1EasyExam

What is the CAP theorem? For a distributed database, what does it mean to choose CP versus AP? Give a real-world example of each choice.

Reveal Worked Solution
Under network partition (P), a distributed store trades strong Consistency (CP: reject writes on minority side, e.g., HBase) against high Availability (AP: accept writes everywhere and reconcile later, e.g., Cassandra).
Q2EasyICA

Explain the difference between a document store (e.g., MongoDB), a key-value store (e.g., Redis), and a column-family store (e.g., Cassandra). Give a use case suited to each.

Reveal Worked Solution
Document stores hold flexible nested JSON documents (product catalogs); key-value stores offer sub-millisecond cache/session lookups; wide-column stores optimize high-write time-series/IoT partition scans.
Q3EasyExam

What is a vector database? How does it differ from a relational database in terms of data representation and query type? Name one commercial vector database.

Reveal Worked Solution
A vector database stores high-dimensional dense embeddings and executes approximate nearest-neighbor (ANN) similarity queries (for example, Qdrant, Milvus, or pgvector) instead of exact relational predicates.
Q1IntermediateExam

Explain how a RAG (Retrieval Augmented Generation) pipeline works. What role does the vector database play? What are the three failure modes: retrieval miss, hallucination, and context overflow: and how can each be mitigated?

Reveal Worked Solution
RAG embeds user queries, retrieves top-k semantically similar chunks from a vector DB, and grounds LLM generation on those chunks. Mitigate retrieval misses via hybrid BM25+vector search, hallucinations via citation constraints, and context overflow via re-ranking and chunk budgeting.
Q2IntermediateProject

Design a schema for storing document embeddings in a vector database for a university knowledge base. What chunking strategy would you use? What metadata would you store alongside each vector? How would you handle document updates?

Reveal Worked Solution
Chunk documents into 300–500 token overlapping spans, store (chunk_id, doc_id, section, version, updated_at, embedding) as metadata, and delete-then-upsert stale chunks keyed by doc_id on document updates.
Q1AdvancedProject

A fintech startup needs to store transaction records (strong consistency required), user preference profiles (flexible schema, fast reads), and a semantic search feature over support tickets. Design a polyglot persistence architecture using three different database systems. Justify each choice and explain how you would maintain consistency across them.

Reveal Worked Solution
Route ACID payment ledgers to PostgreSQL (CP relational), user preference JSON profiles to MongoDB, and ticket embeddings to Qdrant/pgvector. Propagate committed ledger/ticket events asynchronously via an outbox pattern and CDC (Debezium/Kafka) to avoid brittle distributed two-phase commits.