Database, Past Papers, UOS Main Campus

Database Systems Past Paper 2026 – BS CS, IT & SE 2nd Semester UOS (CMPC-5203)

ProgramBS CS
Semester2nd
Year2026
Course codeCMPC-5203
AnswersSolved ✓

University of Sargodha Database Systems (CMPC-5203) paper for AD/BS Computer Science, IT and Software Engineering 2nd semester, 2026 exam (40 marks, 2:30 hours) – one of the newest papers on the site. The paper has been retyped, and solved answers are given below for all 8 short questions and all five long questions, including the hospital ERD, normalization to 3NF and tested SQL queries.

Solved answers

Q1 – Short answers (8 × 2)

i. Purpose of a “lock” in concurrency control: A lock is a variable attached to a data item that controls access by concurrent transactions. A shared (S) lock allows many transactions to read; an exclusive (X) lock allows only one to write. Locks prevent lost updates, dirty reads and inconsistent analysis, and protocols like Two-Phase Locking (2PL) guarantee serializable schedules.

ii. NoSQL database vs relational database: A NoSQL database stores data without fixed relational tables — as documents (MongoDB), key-value pairs (Redis), wide columns (Cassandra) or graphs (Neo4j). Relational databases use a fixed schema, tables, joins, SQL and strict ACID transactions; NoSQL uses a flexible schema, scales horizontally across many servers and often uses eventual consistency (BASE).

iii. Projection in relational databases: Projection (π) is a unary relational-algebra operation that selects certain columns (attributes) of a relation and removes duplicate rows. Example: πName, City(Customer) returns only the Name and City columns. In SQL: SELECT DISTINCT Name, City FROM Customer.

iv. Cartesian Product in relational algebra: R × S combines every tuple of R with every tuple of S. If R has m tuples and a attributes and S has n tuples and b attributes, the result has m × n tuples and a + b attributes. It is usually followed by a selection, e.g. σR.id = S.id(R × S), which is a join.

v. Index in a database and why it is used: An index is a separate data structure (usually a B+ tree or hash) on one or more columns that stores key values with pointers to rows. It speeds up searching, sorting and joins because the DBMS does not have to scan the whole table, e.g. CREATE INDEX idx_city ON Customer(City). The cost is extra storage and slower inserts/updates.

vi. Union operation with example: R ∪ S returns all tuples that are in R, in S, or in both, with duplicates removed. Both relations must be union-compatible (same number of attributes with matching domains). Example: if CS_Students = {Ali, Sara} and IT_Students = {Sara, Usman}, then CS_Students ∪ IT_Students = {Ali, Sara, Usman}.

vii. Purpose of foreign keys: A foreign key is an attribute in one table that refers to the primary key of another table, e.g. Orders.CustomerID → Customer.CustomerID. It links related tables so they can be joined, and it enforces that a child row cannot refer to a parent row that does not exist.

viii. Referential integrity: Referential integrity is the rule that every non-null foreign key value must match an existing primary key value in the referenced table. The DBMS enforces it by rejecting such inserts/updates, and on delete/update of a parent row it applies RESTRICT, CASCADE, SET NULL or SET DEFAULT.

Q2 – File-based systems vs DBMS

A file-based system stores each application’s data in its own separate files (e.g. text or binary files) and every program contains its own code to read and write them. A DBMS is software that stores all related data in one integrated database and gives controlled, shared access to it through a query language such as SQL.

PointFile-based systemDBMS
Data storageSeparate files for each applicationOne integrated, shared database
RedundancyHigh – same data copied in many filesControlled – data stored once and shared
ConsistencyCopies can disagreeUpdates in one place keep data consistent
Data accessA new program is needed for every new queryAd-hoc queries with SQL
Program–data dependencePrograms depend on the file formatData independence (logical and physical)
SecurityOnly OS file permissionsUsers, roles, views and privileges
IntegrityConstraints hidden inside program codeDeclared constraints (PK, FK, CHECK)
ConcurrencyNot handled; updates can be lostLocking and transactions (ACID)
Backup & recoveryManualBuilt-in logs, backups and recovery
Cost / complexityCheap and simpleMore costly software, needs a DBA

Limitations of file systems that led to databases:

  1. Data redundancy and inconsistency – the same student address kept in the fees file and the exam file gets out of date in one of them.
  2. Difficulty in accessing data – every new report needs a new program.
  3. Data isolation – data scattered in different files and formats is hard to combine.
  4. Integrity problems – rules like “marks ≤ 100” are buried in program code and hard to change.
  5. Atomicity problems – a crash during a fund transfer can debit one account without crediting the other.
  6. Concurrent-access anomalies – two users updating the same file can overwrite each other.
  7. Security problems – it is hard to let a user see only part of the data.
  8. Program–data dependence – changing the file structure means changing all programs.

The DBMS approach solves these by central control of data, a data dictionary, query languages, constraints, transactions, concurrency control and recovery.

Q3 – Backup and recovery

Backup is making a copy of the database (data files, and usually the transaction log) on separate storage so it can be restored later. Recovery is the process of restoring the database to a correct, consistent state after a failure, using the backup and the log.

Why they are essential: hardware/disk failures, software bugs, power cuts, human mistakes (e.g. an accidental DELETE), viruses/ransomware and disasters can destroy or corrupt data. Backup and recovery protect against data loss, keep the database consistent (ACID durability), reduce downtime and meet legal/business requirements.

Types of backups:

  • Full backup – copies the whole database. Simple to restore but slow and large.
  • Incremental backup – copies only data changed since the last backup of any type. Fast and small, but restore needs the full backup plus every incremental.
  • Differential backup – copies data changed since the last full backup. Restore needs only the full + the latest differential.
  • Transaction-log backup – copies the log records, allowing point-in-time recovery.
  • Hot (online) vs cold (offline) backup – taken while the database is running vs after shutting it down.
  • Logical vs physical backup – SQL dump of objects (e.g. mysqldump) vs copy of the data files.

Recovery techniques:

  • Log-based recovery – the DBMS writes every change (transaction id, item, old value, new value) to a log before applying it (Write-Ahead Logging). After a failure it redoes committed transactions and undoes uncommitted ones.
  • Deferred update (NO-UNDO/REDO) – changes are written to the database only after commit, so recovery needs only redo.
  • Immediate update (UNDO/REDO) – changes may reach the database before commit, so both undo and redo are needed.
  • Checkpoints – the DBMS periodically flushes buffers and writes a checkpoint record, so recovery starts from the last checkpoint instead of the start of the log.
  • Shadow paging – keeps a shadow page table of the old state; on commit the new page table replaces it, on failure the shadow is used (no log needed).
  • Restore from backup + roll forward – for media failure, restore the last backup and re-apply the archived logs.
System crash recoveryTransaction failure recovery
CausePower failure, OS/DBMS crash; main memory lost, disk intactLogical error, deadlock, constraint violation or user abort in one transaction
ScopeAll transactions active at the time of the crashOnly the failed transaction
ActionUse the log from the last checkpoint: REDO committed, UNDO uncommitted transactionsROLLBACK: UNDO the changes of that transaction only
Other transactionsAll are affected, the system restartsContinue normally

Q4 – ERD for Hospital Management System

1) Entities: Doctor, Patient, Appointment, Prescription.

2) Relationships: Doctor attends Appointment; Patient books Appointment; Appointment has Prescription. The many-to-many relationship between Doctor and Patient is resolved through the Appointment entity (an associative entity).

3) Cardinality:

RelationshipCardinalityMeaning
Doctor – Appointment1 : MOne doctor has many appointments; each appointment is with one doctor
Patient – Appointment1 : MOne patient has many appointments; each appointment is for one patient
Doctor – Patient (through Appointment)M : NA doctor sees many patients, a patient sees many doctors
Appointment – Prescription1 : MOne appointment may have many prescribed medicines (0..M)

4) Attributes (PK underlined, FK marked):

EntityAttributes
DoctorDoctorID, Name, Specialization, PhoneNumber
PatientPatientID, Name, Gender, DateOfBirth, PhoneNumber
AppointmentAppointmentID, Date, Time, RoomNumber, DoctorID (FK), PatientID (FK)
PrescriptionPrescriptionID, MedicineName, Dosage, Duration, AppointmentID (FK)

Prescription can also be modelled as a weak entity identified by (AppointmentID, MedicineName); a separate PrescriptionID keeps it simple.

5) ERD:

DOCTORPK DoctorIDNameSpecializationPhoneNumberPATIENTPK PatientIDNameGenderDateOfBirthPhoneNumberAPPOINTMENTPK AppointmentIDDate, Time, RoomNumberFK DoctorIDFK PatientIDPRESCRIPTIONPK PrescriptionIDMedicineNameDosage, DurationFK AppointmentID1M1M1Mattendsbookshas
ERD: Doctor 1–M Appointment M–1 Patient; Appointment 1–M Prescription

Q5 – Normalization (1NF → 2NF → 3NF)

Functional dependencies: StudentID → StudentName; CourseID → CourseName, InstructorID, Credits; InstructorID → InstructorName, InstructorPhone. The key of the table is the composite key (StudentID, CourseID).

1) 1NF: Every cell already holds a single atomic value and there are no repeating groups, so the table is already in 1NF, with primary key (StudentID, CourseID). Problems still exist: “John Smith, 555-1234” is repeated (update anomaly), a new course cannot be added until a student enrols (insertion anomaly), and deleting student 102 loses course CS102 (deletion anomaly).

2) 2NF (remove partial dependencies on part of the composite key): StudentName depends only on StudentID, and CourseName, InstructorID, InstructorName, InstructorPhone, Credits depend only on CourseID. Split:

StudentIDStudentName
101Alice
102Bob
103Charlie
104Alice
Student
StudentIDCourseID
101CS101
102CS102
103CS101
104CS103
Enrollment
CourseIDCourseNameInstructorIDInstructorNameInstructorPhoneCredits
CS101Data ScienceI01John Smith555-12343
CS102AII02Jane Doe555-56784
CS103DatabaseI03Mike Brown555-98763
Course (2NF)

3) 3NF (remove transitive dependencies): in Course, CourseID → InstructorID → InstructorName, InstructorPhone. Move instructor details to their own table:

CourseIDCourseNameInstructorID (FK)Credits
CS101Data ScienceI013
CS102AII024
CS103DatabaseI033
Course (3NF)
InstructorIDInstructorNameInstructorPhone
I01John Smith555-1234
I02Jane Doe555-5678
I03Mike Brown555-9876
Instructor

4) Final 3NF schema:

  • Student (StudentID, StudentName)
  • Course (CourseID, CourseName, Credits, InstructorID → Instructor)
  • Instructor (InstructorID, InstructorName, InstructorPhone)
  • Enrollment (StudentID → Student, CourseID → Course)

Q6 – SQL queries

“Order” is a reserved word in SQL, so the table is written as Orders (or [Order]). Parts (b), (c) and (d) need to know which products are in which order, which the given tables do not store. The standard solution is a linking table OrderDetails(OrderID, ProductID, Quantity), with (OrderID, ProductID) as the primary key and both columns as foreign keys. The queries below were tested in SQLite on sample OrderDetails rows.

(a) Customer name, order ID and total amount for all orders:

SELECT c.CustomerName, o.OrderID, o.TotalAmount
FROM Customer c
JOIN Orders o ON o.CustomerID = c.CustomerID
ORDER BY o.OrderID;
CustomerNameOrderIDTotalAmount
Alice101250.00
Bob102180.00
Alice103300.00
Charlie104120.00

Diana has no order, so she does not appear (use LEFT JOIN if customers without orders should also be listed).

(b) Total quantity of each product sold:

SELECT p.ProductID, p.ProductName,
       COALESCE(SUM(od.Quantity), 0) AS TotalQuantity
FROM Product p
LEFT JOIN OrderDetails od ON od.ProductID = p.ProductID
GROUP BY p.ProductID, p.ProductName;

(c) Products that have never been ordered:

SELECT p.ProductID, p.ProductName
FROM Product p
WHERE p.ProductID NOT IN (SELECT od.ProductID FROM OrderDetails od);

-- or with LEFT JOIN
SELECT p.ProductID, p.ProductName
FROM Product p
LEFT JOIN OrderDetails od ON od.ProductID = p.ProductID
WHERE od.ProductID IS NULL;

(d) Customers from “New York” who have ordered a “Laptop”:

SELECT DISTINCT c.CustomerID, c.CustomerName
FROM Customer c
JOIN Orders o        ON o.CustomerID = c.CustomerID
JOIN OrderDetails od ON od.OrderID  = o.OrderID
JOIN Product p       ON p.ProductID = od.ProductID
WHERE c.City = 'New York'
  AND p.ProductName = 'Laptop';

Only Alice lives in New York. If her orders contain a laptop, the result is Alice. DISTINCT stops her name from appearing twice when two of her orders contain a laptop.

Save this paper for offline studyDownload the question paper, or save the paper together with all solved answers as a PDF.
↓ Download Paper (JPG)

About Saif R

An educator and technology enthusiast passionate about empowering students through quality education and digital learning. Dedicated to making academic resources and opportunities accessible to everyone.