Tribhuvan University
Faculty of Management
Office of the Dean
2024 AD / Regular Examination
Candidates are required to give their answers in their own words as far as practicable. The figures in the margin indicate full marks.
Section A
Brief Answer Questions :
[10*1=10]- [1]
Define Database Language.
View model solution
Definition of Database Language
A database language is a specialized computer language provided by a Database Management System (DBMS) that allows users, application programmers, and administrators to specify database schemas, express queries, manipulate stored data instances, and enforce security authorizations.
The primary database language in modern relational systems is SQL (Structured Query Language), which encompasses sub-languages including:
- DDL (Data Definition Language): For defining schema structures (
CREATE,ALTER,DROP). - DML (Data Manipulation Language): For data retrieval and manipulation (
SELECT,INSERT,UPDATE,DELETE). - DCL (Data Control Language): For privilege management (
GRANT,REVOKE). - TCL (Transaction Control Language): For managing transaction states (
COMMIT,ROLLBACK).
- DDL (Data Definition Language): For defining schema structures (
- [1]
Write a SQL statement for update operation.
View model solution
SQL Statement for UPDATE Operation
The SQL
UPDATEstatement is a Data Manipulation Language (DML) command used to modify existing data values in one or more columns of a table based on an optional filtering condition.General Syntax:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;Concrete Example:
-- Increase the salary of employees in department 10 by 10% UPDATE Employee SET salary = salary * 1.10 WHERE dept_id = 10;Note: If the
WHEREclause is omitted, all rows across the entire table will be updated. - [1]
What is unary Relationship?
View model solution
Unary Relationship (Recursive Relationship)
A unary relationship (also known as a recursive relationship) is a relationship type in which the same entity set participates more than once in distinct roles.
+------------------+ | EMPLOYEE | +--------+---------+ | ^ (subordinate) (manager) | | v | +--------+---------+ | Manages | +------------------+Real-World Examples:
- Employee Management: An
Employeemanages otherEmployees (Role 1: Manager, Role 2: Subordinate). - Course Prerequisites: A
Courserequires anotherCourseas a prerequisite (Role 1: Main Course, Role 2: Prerequisite Course). - Bill of Materials: A
Partcontains other componentParts.
- Employee Management: An
- [1]
List any four types of attributes in ER Model.
View model solution
Four Types of Attributes in ER Model
In the Entity-Relationship (ER) model, attributes represent the properties or characteristics describing an entity set:
- Simple (Atomic) Attribute: An attribute that cannot be divided into sub-parts (e.g.,
Age,Salary,Gender). - Composite Attribute: An attribute composed of multiple sub-attributes, each with its own semantic meaning (e.g.,
Namecomposed ofFirst_Name,Middle_Name, andLast_Name). - Multivalued Attribute: An attribute that can hold more than one value for a single entity instance (e.g.,
Phone_Numbers,Degrees; represented by a double oval). - Derived Attribute: An attribute whose value is computed dynamically from other stored attributes or system variables (e.g.,
Agederived fromDate_of_Birth; represented by a dashed oval).
- Simple (Atomic) Attribute: An attribute that cannot be divided into sub-parts (e.g.,
- [1]
Define serializable schedule.
View model solution
Definition of Serializable Schedule
A concurrent execution schedule
of multiple transactions is called a serializable schedule if its outcome (the final database state) is computationally equivalent to the outcome produced by some purely serial schedule of the same transactions (where transactions execute strictly one after another without interleaving). Serializability is the formal criterion of correctness for concurrent transaction processing:
- Conflict Serializability: The schedule can be transformed into a serial schedule by swapping non-conflicting adjacent operations. Tested via a cycle-free precedence (serialization) graph.
- View Serializability: The schedule produces the same final state and read/write dependencies as a serial schedule.
- [1]
What is big data?
View model solution
What is Big Data?
Big Data refers to datasets whose size, velocity of generation, and diversity of structure exceed the processing, storage, and querying capabilities of conventional relational database management systems (RDBMS) and standard analytical software tools.
It is formally defined by the 5 V’s Framework:
- Volume: Immense data magnitude (petabytes to exabytes).
- Velocity: Streaming data generation at real-time speeds.
- Variety: Heterogeneous formats (structured tables, semi-structured JSON, unstructured video/text).
- Veracity: Data cleanliness, noise, and authenticity.
- Value: Actionable insights extracted through advanced analytics.
- [1]
Define deferred data update.
View model solution
Deferred Data Update (NO-UNDO / REDO)
Deferred data update is a log-based database recovery technique in which all update operations of an active transaction are written only to the log file (in memory and disk) while the transaction is executing, and no modifications are written to the physical database on disk until the transaction successfully reaches its commit point.
Recovery Implication:
- NO-UNDO: Since uncommitted updates are never flushed to the physical database on disk, if a transaction aborts or the system crashes, no undo operations are necessary.
- REDO: Any transaction that committed before the crash must have its operations redone (REDO) from the log to ensure changes reach non-volatile physical storage.
- [1]
What is importance of creating view?
View model solution
Importance of Creating Views
A View is a virtual table defined by an underlying SQL query that provides powerful software engineering benefits:
- Data Security & Row/Column Access Control: Hides sensitive columns (e.g., credit card numbers, passwords, salaries) from unauthorized users by exposing only permissible slices of tables.
- Query Simplification: Encapsulates complex multi-table
JOINs,GROUP BYaggregations, and subqueries into a simple virtual table query. - Logical Data Independence: Shields client applications from structural changes in underlying physical base tables.
- Customized Data Representation: Provides tailored presentations and renamed columns for specific organizational user departments.
- [1]
State 3NF.
View model solution
Third Normal Form (3NF)
A relation schema
is in Third Normal Form (3NF) if: - It is already in Second Normal Form (2NF).
- No non-prime attribute is transitively dependent on any candidate key of
.
Formal Definition (Codd / Date):
A relation schema
is in 3NF if, for every non-trivial functional dependency that holds on , at least one of the following conditions is satisfied: is a superkey of , OR - Each attribute in
is a prime attribute (a member of some candidate key of ).
- [1]
Define Roles.
View model solution
Definition of Roles in ER Model
In an Entity-Relationship (ER) model, a Role is the explicit name or function that an entity plays when participating in a relationship type.
While role names are technically implicit in binary relationships connecting two distinct entity sets (e.g.,
CustomerandAccount), they are strictly required in recursive (unary) relationships where the same entity set participates multiple times.- Example: In the relationship
Manageson the entity setEMPLOYEE:- Entity occurrence 1 plays the role of
Manager. - Entity occurrence 2 plays the role of
Subordinate/Worker.
- Entity occurrence 1 plays the role of
- Example: In the relationship
Section B
Short Answer Questions : ( Attempt aby FIVE Questions )
[5*3=15]- [3]
Describe shadow paging concept in brief.
View model solution
Shadow Paging Recovery Technique
Shadow paging is an alternative, non-log-based database recovery mechanism where database pages are maintained via two separate page directories:
+------------------------------------+ | Database Root | +-----------------+------------------+ | +---------------+---------------+ | | v v +--------------------+ +--------------------+ | Current Page Table | | Shadow Page Table | | (In Volatile | | (On Non-Volatile| | Memory) | | Disk) | +---------+----------+ +---------+----------+ | | +---------------+---------------+ | v +-----------------------+ | Physical Database | | Disk Pages | +-----------------------+Operational Workflow:
- Two Page Tables:
- Shadow Page Table: Stored permanently on non-volatile disk; represents the database state at the start of the transaction. Never updated during transaction execution.
- Current Page Table: Maintained in main memory; tracks live database page pointers during execution.
- Write Operation (Copy-on-Write): When a page is modified, the DBMS allocates a new free physical disk block, writes the modified data to the new block, and updates the pointer in the Current Page Table to point to the new block. The original block remains unchanged.
- Commit Point: At commit, the Current Page Table is flushed to disk, and the single database root pointer is atomically updated to point to the new table, making it the new Shadow Page Table.
- Abort / Crash Recovery: If the transaction fails, the Current Page Table is discarded, and the root pointer remains pointed at the unaltered Shadow Page Table. Recovery is instantaneous with no UNDO and no REDO needed.
Limitations:
- Severe disk page fragmentation and garbage collection overhead.
- Two Page Tables:
- [3]
Who is DBA? List the roles of DBA.
View model solution
Database Administrator (DBA) and Roles
Who is a DBA?
A Database Administrator (DBA) is a highly skilled technical professional or specialized team responsible for the centralized operational management, performance, configuration, security, integrity, and ongoing maintenance of an organization’s database systems.
Key Roles and Responsibilities of a DBA:
- Schema Definition & Modification: Formulates the physical and logical database schemas, writes data definition statements, and implements schema alterations to support evolving business requirements.
- Storage Structure & Access-Method Definition: Determines physical disk layouts, file organizations, block sizes, clustering, and index creation (B-trees, hash indexes) for optimal query throughput.
- Granting User Authorizations & Security Control: Administers user accounts, assigns role-based permissions (
GRANT/REVOKE), prevents unauthorized data access, and maintains data privacy. - Routine Backup and Disaster Recovery: Establishes automated daily/weekly backup procedures, monitors Write-Ahead Logs, and executes disaster recovery drills to ensure zero data loss.
- Performance Tuning & Optimization: Analyzes query execution plans, identifies bottlenecks, monitors server hardware utilization, and tunes database cache buffers.
- [3]
Explain the concept of Time stamp ordering concurrency control techniques.
View model solution
Timestamp Ordering Concurrency Control Technique
The Timestamp Ordering (TO) protocol is a non-locking, pessimistic concurrency control technique that ensures conflict serializability by assigning each transaction a globally unique timestamp
when it begins. Conflicting operations are executed strictly in timestamp order. System Timestamps Maintained:
For every database data item
, the DBMS maintains two timestamp values: : The largest timestamp of any transaction that successfully wrote . : The largest timestamp of any transaction that successfully read .
Basic Timestamp Ordering Protocol Rules:
-
Transaction
issues : - If
, then is attempting to read an overwritten value. Reject and rollback (abort and restart with a newer timestamp). - If
, execute and set:
- If
-
Transaction
issues : - If
, then is attempting to produce a value that should have been read by a younger transaction. Reject and rollback . - If
, then is attempting to overwrite a newer value. Reject and rollback (or ignore the write under the Thomas Write Rule). - Otherwise, execute
and set:
- If
Major Advantage:
- Guarantees freedom from deadlocks, as transactions never wait on locks.
- [3]
Illustrate how composite attribute is reduced into relational schema with example?
View model solution
Mapping Composite Attributes into Relational Schema
Conceptual Rule:
In the ER-to-Relational mapping algorithm, a composite attribute is not directly mapped as a single column. Instead, it is flattened by replacing the composite attribute with its simple, atomic component attributes. The composite attribute itself is dropped from the relational schema.
Step-by-Step Illustration:
Consider an entity
CUSTOMERin an ER model with:- Primary key:
Customer_ID - Simple attribute:
Email - Composite attribute:
Full_Name(components:First_Name,Middle_Name,Last_Name) - Composite attribute:
Address(components:Street_No,City,Postal_Code)
[CUSTOMER] |--- Customer_ID (Key) |--- Email |--- Full_Name (Composite) | |--- First_Name | |--- Middle_Name | |--- Last_Name |--- Address (Composite) |--- Street_No |--- City |--- Postal_CodeResulting Relational Schema:
SQL DDL Implementation:
CREATE TABLE Customer ( customer_id INT PRIMARY KEY, email VARCHAR(100) NOT NULL UNIQUE, first_name VARCHAR(30) NOT NULL, middle_name VARCHAR(30), last_name VARCHAR(30) NOT NULL, street_no VARCHAR(50), city VARCHAR(50), postal_code VARCHAR(10) ); - Primary key:
- [3]
Explain constraints of generalization and specialization in ER model.
View model solution
Constraints on Generalization and Specialization
In Extended Entity-Relationship (EER) modeling, generalization and specialization hierarchies are governed by two independent structural constraints:
EER Constraints | +-------------------+-------------------+ | | Disjointness Constraint Completeness Constraint | | +-----+-----+ +-----+-----+ | | | | Disjoint Overlap Total Partial (d) (o) (Double Line)(Single Line)
1. Disjointness Constraint
Specifies whether an entity instance can belong to more than one specialized subclass simultaneously:
- Disjoint (
d): Subclasses must be mutually exclusive. An entity can belong to at most one subclass.- Example: In a
VEHICLEsuperclass, an instance can be aCARor aTRUCK, but not both simultaneously.
- Example: In a
- Overlapping (
o): Subclasses are not mutually exclusive. An entity can belong to multiple subclasses at the same time.- Example: In a university, a
PERSONcan be both anEMPLOYEEand aSTUDENT.
- Example: In a university, a
2. Completeness (Mandatory / Optional) Constraint
Specifies whether an entity in the superclass must participate in at least one subclass:
- Total Specialization (Double Line): Every entity in the superclass must belong to at least one subclass.
- Example: An
ACCOUNTmust be either aSAVINGS_ACCOUNTor aCHECKING_ACCOUNT.
- Example: An
- Partial Specialization (Single Line): An entity in the superclass does not have to belong to any subclass.
- Example: In an
EMPLOYEEsuperclass with subclassENGINEER, some employees may be accountants or managers who do not belong toENGINEER.
- Example: In an
- Disjoint (
- [3]
What is the importance of database security?
View model solution
Importance of Database Security
Database security is of critical strategic importance because modern enterprise databases store confidential proprietary information, intellectual property, personal identifiable information (PII), and financial transaction records.
Key Reasons for Database Security:
- Preserving the CIA Triad:
- Confidentiality: Protects sensitive data from unauthorized interception and unauthorized disclosure.
- Integrity: Prevents unauthorized, improper, or accidental modification or deletion of vital data.
- Availability: Guarantees authenticated users uninterrupted access to database services during hardware faults or DoS attacks.
- Protection Against Cyber Threats: Prevents destructive external attacks such as SQL Injection (SQLi), brute force authentication attacks, privilege escalation, and ransomware encryption.
- Regulatory & Legal Compliance: Ensures adherence to strict national and international data protection laws (e.g., GDPR, HIPAA, Nepal Electronic Transactions Act) to prevent crippling financial penalties.
- Reputational and Financial Safeguards: A data breach causes devastating loss of customer trust, corporate valuation drops, and severe legal liabilities.
- Preserving the CIA Triad:
Section C
Long Answer Questions : ( Attempt any THREE Questions )
[3*5=15]- [5]
Explain any four types of Database user.
View model solution
Four Types of Database Users
Database users are classified into distinct categories based on their technical proficiency, access requirements, and the interfaces they use to interact with the DBMS:
+-------------------------------------------------------------------------+ | Database User Spectrum | +-------------------+-------------------+-----------------+---------------+ | DBA | Database Designer | Application Dev | End Users | | High Privilege | Schema Modeling | DML Programming | Daily Queries | +-------------------+-------------------+-----------------+---------------+
1. Database Administrator (DBA)
- Description: The chief authority possessing supreme administrative privileges over the entire database system.
- Core Responsibilities:
- Installing and configuring DBMS software across hardware servers.
- Creating schemas, storage layouts, and system indexes.
- Managing user accounts, assigning permissions (
GRANT/REVOKE), and enforcing security policies. - Scheduling automated backups, monitoring system performance, and executing disaster recovery procedures.
2. Database Designers
- Description: Information architects responsible for identifying enterprise data requirements and engineering database models prior to database deployment.
- Core Responsibilities:
- Interviewing business stakeholders to capture entities, attributes, and business rules.
- Constructing conceptual schemas using Entity-Relationship (ER/EER) diagrams.
- Converting conceptual schemas into normalized relational schemas (1NF through BCNF) to prevent update anomalies.
3. Application Programmers / Software Developers
- Description: Technical professionals who write application programs that interact with the database engine.
- Core Responsibilities:
- Writing code in high-level programming languages (Java, C#, Python, JavaScript).
- Embedding SQL Data Manipulation Language (DML) statements via APIs, ODBC/JDBC drivers, or ORM frameworks.
- Building intuitive web and mobile user interfaces, error-handling routines, and transactional business logic.
4. End Users (Parametric and Casual Users)
- Description: Non-technical or business professionals who query and update the database during daily business operations.
- Subcategories:
- Naive / Parametric Users: Represent the vast majority of users. They interact exclusively through pre-built graphical user interfaces, web forms, or POS terminals without knowing SQL (e.g., bank tellers, airline ticketing agents, retail cashiers).
- Sophisticated Users: Business analysts, researchers, and data scientists who write ad-hoc SQL queries and use analytics tools to extract custom managerial reports.
- [5]
How normalization helps to design good database? Explain second normal form with example.
View model solution
How Normalization Helps Design a Good Database & Second Normal Form (2NF)
How Normalization Helps in Database Design:
Normalization is a formal mathematical process developed by E.F. Codd to analyze relational schemas based on their functional dependencies (FDs) and primary keys:
- Elimination of Data Redundancy: Prevents repetitive recording of identical facts, drastically saving disk storage.
- Prevention of Modification Anomalies: Completely eradicates insertion, deletion, and update anomalies.
- Data Integrity & Consistency: Ensures changes made to an entity update a single tuple, preventing contradictory database states.
- Scalability: Produces lean, modular tables that easily accommodate future schema additions without breaking existing relationships.
Second Normal Form (2NF) Definition:
A relation schema
is in Second Normal Form (2NF) if and only if: - It is already in First Normal Form (1NF).
- No non-prime attribute is partially dependent on any candidate key of
. That is, every non-prime attribute must be fully functionally dependent on the whole candidate key.
Note: Partial dependency can only exist when the candidate key is a composite key (composed of two or more attributes).
Step-by-Step Example of 2NF Decomposition:
Consider the relation
STUDENT_COURSE_ENROLLMENT:- Attributes:
(Student_ID, Course_ID, Student_Name, Course_Name, Grade) - Composite Primary Key:
{Student_ID, Course_ID}
Functional Dependencies (FDs):
(Student_ID, Course_ID) -> Grade(Full Dependency on Key)Student_ID -> Student_Name(Partial Dependency: depends on part of PK)Course_ID -> Course_Name(Partial Dependency: depends on part of PK)
Anomalies Present:
- Insertion Anomaly: Cannot insert a new course until a student enrolls in it.
- Deletion Anomaly: Deleting the only student enrolled in a course deletes the course name.
- Update Anomaly: If a student changes their name, multiple enrollment rows must be updated.
2NF Decomposition:
To achieve 2NF, decompose the table into three separate relations by isolating partial dependencies:
STUDENTRelation:- Schema:
Student(Student_ID [PK], Student_Name)
- Schema:
COURSERelation:- Schema:
Course(Course_ID [PK], Course_Name)
- Schema:
ENROLLMENTRelation:- Schema:
Enrollment(Student_ID [FK], Course_ID [FK], Grade, PRIMARY KEY(Student_ID, Course_ID))
- Schema:
Result: Every non-key attribute is now fully dependent on its table’s primary key. The schema is in 2NF.
- [5]
Discuss any four constraints available in database with example.
View model solution
Four Relational Database Constraints with Examples
Database constraints are declarative assertions and rules enforced by the DBMS data integrity engine to guarantee that data entry, modifications, and deletions do not corrupt database consistency.
+----------------------------------------------------------------------+ | Core Database Constraints | +-------------------+--------------------+-----------------------------+ | Constraint | Scope | Rule Enforced | +-------------------+--------------------+-----------------------------+ | 1. Domain | Single Attribute | Valid data types & ranges | | 2. Entity Int. | Primary Key | Uniqueness & NOT NULL | | 3. Referential | Foreign Key | Value must exist in parent | | 4. Key / UNIQUE | Candidate Keys | No duplicate values allowed | +-------------------+--------------------+-----------------------------+
1. Domain Constraint
- Concept: Specifies that every value stored in an attribute must be an atomic element belonging to the defined domain/data type, including range, format, and
NOT NULLrules. - Example:
CREATE TABLE Employee ( emp_id INT, gender CHAR(1) CHECK (gender IN ('M', 'F', 'O')), salary DECIMAL(10, 2) CHECK (salary >= 10000) );
2. Entity Integrity Constraint
- Concept: Specifies that no primary key value can be
NULLbecause primary key values are used to identify individual tuples in a relation. - Example:
CREATE TABLE Department ( dept_id INT PRIMARY KEY, -- Automatically enforces UNIQUE and NOT NULL dept_name VARCHAR(50) NOT NULL );
3. Referential Integrity Constraint
- Concept: Maintained between two relations to preserve consistency between tuples. A foreign key in a referencing relation must either match a valid primary key value in the referenced relation or be
NULL. - Example:
CREATE TABLE Employee ( emp_id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, dept_id INT, CONSTRAINT fk_emp_dept FOREIGN KEY (dept_id) REFERENCES Department(dept_id) ON DELETE CASCADE ON UPDATE CASCADE );
4. Key Constraint (UNIQUE Constraint)
- Concept: Specifies that all values in a designated column or set of columns must be distinct across all rows in the relation, while permitting optional
NULLvalues. - Example:
CREATE TABLE UserAccount ( user_id INT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(100) NOT NULL UNIQUE ); - Concept: Specifies that every value stored in an attribute must be an atomic element belonging to the defined domain/data type, including range, format, and
- [5]
Explain the Desirable Properties of Transaction.
View model solution
Desirable Properties of Transaction (ACID Properties)
A database transaction is a sequence of read and write operations treated as a single logical unit of processing. To guarantee data reliability, especially during concurrent execution and unforeseen system failures, a transaction must adhere to the ACID properties:
1. Atomicity (“All or Nothing”)
- Principle: A transaction must be an indivisible unit of work. Either all operations of the transaction succeed and commit, or in the event of an error, the entire transaction is rolled back and has no effect on the database.
- Enforcing Component: The Recovery Manager using undo log records.
- Example: During an online banking transfer, if money is debited from Sender A but a network failure prevents crediting Receiver B, atomicity forces the database to undo the debit from Sender A.
2. Consistency (State Validity)
- Principle: A transaction must take the database from one valid consistent state to another valid consistent state, maintaining all schema constraints, business rules, and cascade invariants.
- Enforcing Component: The Application Program and the DBMS Integrity Subsystem (Primary Keys, Foreign Keys, CHECK constraints).
- Example: The total sum of money across all bank accounts before a transfer must equal the total sum after the transfer completes.
3. Isolation (Independence)
- Principle: The execution of a transaction must not be interfered with by any other concurrently executing transactions. Uncommitted intermediate changes must not be visible to other transactions.
- Enforcing Component: The Concurrency Control Manager using locking mechanisms (2PL) or Timestamp Ordering.
- Isolation Levels (ANSI SQL): Read Uncommitted, Read Committed, Repeatable Read, Serializable.
4. Durability (Permanence)
- Principle: Once a transaction commits successfully, its modifications are permanently recorded in non-volatile storage and will survive any subsequent system crash, power failure, or operating system reboot.
- Enforcing Component: The Recovery Manager using Write-Ahead Logging (WAL) and non-volatile storage caching.
Summary Matrix:
Property Focus Guaranteed By Atomicity Complete execution or complete rollback Log File / UNDO Mechanism Consistency Validity of integrity constraints Application Logic & DBMS Constraints Isolation Concurrency without cross-talk Two-Phase Locking / Serializability Durability Survival across system crashes Write-Ahead Logging (WAL) / REDO
Section D
Comprehensive / Case/Situation Analysis Questions :
[2*10=20]- [10]
Draw an ER diagram for Hospital management system with at least five entity set. Implement the concept of mapping cardinality and extended ER feature. Assume suitable attribute sets for each entity set.
View model solution
Comprehensive ER Diagram Design: Hospital Management System
1. Requirements and Scope Analysis
A modern Hospital Management System requires modeling patient admissions, doctor assignments, departmental organizations, medical appointments, inpatient room allocations, and billing.
2. Identification of Entity Sets and Attributes
PERSON(Superclass Entity):- Attributes:
person_id(PK),name(Composite:first_name,last_name),phone,email,address,dob,gender
- Attributes:
PATIENT(Subclass of Person):- Attributes:
patient_id(PK / FK),blood_group,emergency_contact,medical_history
- Attributes:
DOCTOR(Subclass of Person):- Attributes:
doctor_id(PK / FK),specialization,license_no,consultation_fee
- Attributes:
DEPARTMENT:- Attributes:
dept_id(PK),dept_name,location_floor,contact_extension
- Attributes:
APPOINTMENT:- Attributes:
appointment_id(PK),app_date,app_time,status(Scheduled/Completed/Cancelled)
- Attributes:
ROOM/WARD:- Attributes:
room_no(PK),room_type(General/ICU/Deluxe),daily_charge,status(Occupied/Vacant)
- Attributes:
BILL:- Attributes:
bill_id(PK),total_amount,payment_date,payment_status(Paid/Pending)
- Attributes:
3. Extended ER (EER) Features & Mapping Cardinalities
- Specialization / Generalization Hierarchy:
PERSONis specialized intoPATIENTandDOCTOR.- Constraints: Disjoint (
d) and Partial Specialization (a person can also be administrative staff).
- Relationships and Mapping Cardinalities:
DEPARTMENT—Belongs_To—DOCTOR:. A department employs many doctors; each doctor belongs to exactly one department (Total participation on Doctor). PATIENT—Books—APPOINTMENT:. A patient can book multiple appointments. DOCTOR—Attends—APPOINTMENT:. A doctor attends multiple appointments. PATIENT—Admitted_To—ROOM:. Multiple patients may occupy beds over time; at any instant, an admitted patient is assigned to at most one room. PATIENT—Generates—BILL:. A patient incurs bills for consultations and treatments.
4. Architectural Textual ER Diagram
+---------------------------+ | PERSON | | (person_id, name, phone) | +-------------+-------------+ | / d \ [Disjoint Specialization] +-----+ / \ +----------------------+ +----------------------+ | PATIENT | | DOCTOR | | (patient_id, blood) | | (doctor_id, license) | +---+--------------+---+ +----------+-----------+ | | | | 1 | 1 | 1 (Books) (Admitted_To) (Attends) | | | v N v N v N +-------+-------+ +---+-----------+ +-----+---------+ | APPOINTMENT | | ROOM | | DEPARTMENT | | [app_id, date]| | [room_no, fee]| | [dept_id, name| +---------------+ +---------------+ +---------------+ | (Generates) [1:N] v +---------------+ | BILL | | [bill_id, amt]| +---------------+
5. Converted Relational Schema
Person(person_id [PK], first_name, last_name, phone, email, address, dob, gender)Patient(patient_id [PK/FK references Person], blood_group, emergency_contact)Department(dept_id [PK], dept_name, location_floor)Doctor(doctor_id [PK/FK references Person], specialization, license_no, consultation_fee, dept_id [FK])Room(room_no [PK], room_type, daily_charge, status)Appointment(appointment_id [PK], app_date, app_time, status, patient_id [FK], doctor_id [FK])Admission(admission_id [PK], admission_date, discharge_date, patient_id [FK], room_no [FK])Bill(bill_id [PK], total_amount, payment_date, payment_status, patient_id [FK], appointment_id [FK])
- [10]
Consider following relational database:
Car (reg_no, model, price, color)
Person (pid, name, address, phone)
owns_by(reg_no, pid, date)
Write SQL statement for the following: i) Insert a tuple {1, Ram Bdr, kathmandu} in person relation.
ii) Display the model number with highest price.
iii) Increase the price of each car by 15%.
iv) Find name of person who owns red colored car.v) Display those records of car which model contains at most 4 characters.
View model solution
SQL Solutions for Vehicle-Owner Relational Database
Given Relational Database Schema:
Car(reg_no, model, price, color)Person(pid, name, address, phone)owns_by(reg_no, pid, date)
i) Insert a tuple {1, Ram Bdr, kathmandu} in person relation:
INSERT INTO Person (pid, name, address, phone) VALUES (1, 'Ram Bdr', 'kathmandu', NULL);Note: Since the phone attribute is not provided in the tuple, it is explicitly set to
NULL(or omitted from the column list).
ii) Display the model number with the highest price:
SELECT model FROM Car WHERE price = (SELECT MAX(price) FROM Car);Alternative using ORDER BY and LIMIT (standard ANSI/PostgreSQL/MySQL):
SELECT model FROM Car ORDER BY price DESC LIMIT 1;
iii) Increase the price of each car by 15%:
UPDATE Car SET price = price * 1.15;
iv) Find name of person who owns red colored car:
SELECT DISTINCT p.name FROM Person p JOIN owns_by o ON p.pid = o.pid JOIN Car c ON o.reg_no = c.reg_no WHERE LOWER(c.color) = 'red';Subquery Formulation:
SELECT name FROM Person WHERE pid IN ( SELECT pid FROM owns_by WHERE reg_no IN ( SELECT reg_no FROM Car WHERE LOWER(color) = 'red' ) );
v) Display those records of car whose model contains at most 4 characters:
SELECT * FROM Car WHERE LENGTH(model) <= 4;Alternative using CHAR_LENGTH / LIKE pattern:
SELECT * FROM Car WHERE CHAR_LENGTH(TRIM(model)) <= 4;