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.
ER Model & Foundations
What is the difference between a strong entity and a weak entity in an ER diagram? Give one example of each.
Reveal Worked Solution
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)).List the three types of attributes in an ER model and give an example of each.
Reveal Worked Solution
GPA vs. FullName(First, Last)); (2) Single-valued vs. multi-valued (BirthDate vs. PhoneNumbers); (3) Stored vs. derived (BirthDate vs. Age).What is the purpose of a DBMS? Name two advantages of using a DBMS over flat-file storage.
Reveal Worked Solution
Define cardinality ratio in an ER relationship. What are the four possible cardinality ratios?
Reveal Worked Solution
1:1, 1:N, N:1, and M:N.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
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.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
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.Explain the difference between total and partial participation. In your university ER diagram, which relationships have total participation? Justify each choice.
Reveal Worked Solution
Course section has total participation in Teaches, whereas an Instructor on sabbatical may have partial participation.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
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.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
Relational Model
Define: relation, tuple, attribute, domain, degree, and cardinality. Use a concrete example for each.
Reveal Worked Solution
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.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
StudentID, Email); Primary key: chosen candidate key (StudentID); Foreign key: column referencing a primary/unique key in another table (Enrollment.StudentID referencing Student.StudentID).State the entity integrity constraint and the referential integrity constraint. What happens if either is violated?
Reveal Worked Solution
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
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.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
OrderID inside OrderItem as a foreign key with ON DELETE CASCADE. The primary key of OrderItem is the composite (OrderID, ItemNo).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).Relational Algebra
Name the six core relational algebra operations and briefly describe what each does.
Reveal Worked Solution
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).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)).What is the difference between a natural join and an equi-join? Give an example where the result differs.
Reveal Worked Solution
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.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
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).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
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)).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.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
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.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).SQL Foundations
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;.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.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.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;.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.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.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
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').SQL Intermediate
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;.What does a correlated subquery do? Give a simple example and explain why it can be slower than a join.
Reveal Worked Solution
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.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
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)).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(...)).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
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.SQL Advanced
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
WITH: WITH reg AS (SELECT region, SUM(amount) total FROM Sales GROUP BY region) SELECT * FROM reg WHERE total > (SELECT AVG(total) FROM reg);.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
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
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).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;.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
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.Normalization
Define functional dependency. Give two examples from a university database and identify which is trivial and which is non-trivial.
Reveal Worked Solution
X -> Y states that identical X values determine identical Y values. Trivial: (StudentID, Name) -> StudentID (RHS subset of LHS); Non-trivial: StudentID -> Name.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
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
R(A,B,C) with AB->C, C->B is in 3NF (B is prime) but violates BCNF.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
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.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
{A}+ = {A, B, C, D} via transitivity (A->B, B->C implies A->C; with C->D implies A->D), plus trivial/augmented subsets.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
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.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
Storage & Indexing
What is a B+ tree index? How does it differ from a B-tree? Why do database systems prefer B+ trees?
Reveal Worked Solution
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
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
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
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.Explain static hashing and dynamic (extendible) hashing. When does static hashing perform poorly and how does dynamic hashing address it?
Reveal Worked Solution
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.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
(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.Query Processing & Transactions
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
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
Name three types of read anomalies that can occur without proper isolation. Define each and give an example.
Reveal Worked Solution
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
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.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).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
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.Modern & AI Data Systems
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
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
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
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
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_id, doc_id, section, version, updated_at, embedding) as metadata, and delete-then-upsert stale chunks keyed by doc_id on document updates.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.