0% found this document useful (0 votes)
45 views20 pages

QB Unit - 2 Answers

The document outlines the design of a database schema for an online shopping system, detailing the physical and logical structure of tables including Users, Products, Orders, Order Details, and Reviews. It emphasizes the importance of integrity constraints such as primary keys, foreign keys, and various checks to maintain data consistency and prevent anomalies. The schema ensures efficient management of user data, product information, and order processing while adhering to business rules.

Uploaded by

matphychem6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views20 pages

QB Unit - 2 Answers

The document outlines the design of a database schema for an online shopping system, detailing the physical and logical structure of tables including Users, Products, Orders, Order Details, and Reviews. It emphasizes the importance of integrity constraints such as primary keys, foreign keys, and various checks to maintain data consistency and prevent anomalies. The schema ensures efficient management of user data, product information, and order processing while adhering to business rules.

Uploaded by

matphychem6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT-2

1.Implement database schema for the following tables refine with the
appropriate integrity constraints. How these constraints contribute in
maintain data consistency & avoid anomalies in the organization’s database.
1. Employees( Employee ID, Name, Email, Department ID, Salary)
2. Departments(Department ID, Dept Name, Manager ID).
Answer:

INTRODUCTION:
 A database schema outlines the architecture of a relational database, including tables, fields,
data types, and relationships among entities. It is typically expressed in a formal language
supported by RDBMS and includes integrity constraints that ensure data consistency and
validity.

Types of Database Schemas:

 Physical Schema: Details how data is physically stored on storage devices.

 Logical Schema: Defines the logical structure of the database, including tables and their
relationships.

 View Schema: Represents how data is presented to users, often abstracting the underlying
complexity.

Importance of Integrity Constraints:

 Integrity constraints are rules applied to ensure the accuracy and consistency of
data. They include:

 Primary Key Constraints: Ensure each record is unique.

 Foreign Key Constraints: Maintain relationships between tables.

 Domain Constraints: Define permissible values for attributes (e.g.,


ensuring a salary is positive).

 Entity Integrity Constraints: Prevent null values in primary key fields

PHYSICAL SCHEMA:
EMPLOYEES:
SQL> create table Employees(Eid number(3),Ename varchar2(5),Eemail varchar2(6),
departmentid number(3), salary number(5));

Table created.
SQL> desc Employees

Name Null? Type

----------------------------------------- -------- ----------------------------

EID NUMBER(3)

ENAME VARCHAR2(5)

EEMAIL VARCHAR2(6)

DEPARTMENTID NUMBER(3)

SALARY NUMBER(5)

DEPARTMENTS :

SQL> create table Department(dId number(3),deptname varchar2(5),managerID number(5));

Table created.

SQL> desc Department;

Name Null? Type

----------------------------------------- -------- ----------------------------

DID NUMBER(3)

DEPTNAME VARCHAR2(5)

MANAGERID NUMBER(5)

Integrity Constraints and Their Roles


1. Primary Key Constraints:

o EmployeeID in the Employees table and DepartmentID in the Departments table are
primary keys.

o Ensures that each row in the table is uniquely identifiable.

o Prevents duplicate records and ensures data uniqueness.

2. Foreign Key Constraints:

o DepartmentID in the Employees table references DepartmentID in


the Departments table.

o ManagerID in the Departments table references EmployeeID in the Employees table.

o Ensures referential integrity between tables, meaning a department must exist


before an employee can be assigned to it, and a manager must be an existing
employee.

3. Unique Constraints:
o Email in the Employees table ensures no two employees share the same email.

o ManagerID in the Departments table ensures no two departments have the same
manager.

o Prevents data duplication and ensures logical consistency.

4. NOT NULL Constraints:

o Name, Email, and DeptName cannot be null.

o Ensures that critical data is always present and avoids incomplete records.

5. Check Constraints:

o Salary in the Employees table must be non-negative.

o Ensures that data adheres to business rules (e.g., salaries cannot be negative).

LOGICAL SCHEMA:
EMPLOYEES TABLE:
SQL> insert into Employees values(91,'shrya','mail.m',405,50000);

1 row created.

SQL> insert into Employees values(79,'chnda','mail.m',401,70000);

1 row created.

SQL> insert into Employees values(98,'prtha','mail.m',407,90000);

1 row created.

SQL> insert into Employees values(92,'vedha','mail.m',405,40000);

1 row created.

SQL> select * from Employees;

EID ENAME EEMAIL DEPARTMENTID SALARY

---------- ----- ------ ------------ ----------

91 shrya mail.m 405 50000

79 chnd mail.m 407 70000

98 prtha mail.m 407 90000

92 vedha mail.m 405 40000


DEPARTMENT TABLE:
SQL> insert into Department values(91,'DS',79);

1 row created.

SQL> insert into Department values(79,'AIDS',91);

1 row created.

SQL> insert into Department values(47,'AIML',74);

1 row created.

SQL> insert into Department values(80,'DS',08);

1 row created.

SQL> select * from Department;

DID DEPTN MANAGERID

---------- ----- ----------

91 DS 79

79 AIDS 91

47 AIML 74

80 DS 8

How Constraints Maintain Data Consistency and Avoid


Anomalies
1. Prevent Duplicate Data:

o Primary keys and unique constraints ensure that no duplicate records are inserted,
avoiding redundancy.

2. Ensure Referential Integrity:

o Foreign keys ensure that relationships between tables are valid. For example:

 An employee cannot be assigned to a non-existent department.

 A manager must be an existing employee.

3. Avoid Insertion Anomalies:

o Constraints like NOT NULL and foreign keys prevent the insertion of incomplete or
invalid data.

4. Avoid Update Anomalies:


o Unique constraints ensure that updates do not lead to duplicate or inconsistent data
(e.g., two employees with the same email).

5. Avoid Deletion Anomalies:

o Foreign key constraints prevent the deletion of records that are referenced by other
tables. For example:

 A department cannot be deleted if it has employees assigned to it.

 An employee who is a manager cannot be deleted without reassigning the


manager role.

6. Enforce Business Rules:

o Check constraints (e.g., non-negative salary) ensure that data adheres to


organizational rules.

Conclusion:
implementing these integrity constraints not only enhances the reliability of the database but also
supports efficient data management by ensuring that all data adheres to predefined rules, thus
maintaining overall data quality and coherence within the organization’s database.

2.Designa Database schema for the course registration system based on the
following requirements. Clearly define the tables, fields, and integrity
constraints like Primary key, Not Null, Unique, Foreign Key, and Check
constraints.
i. Students(Student ID, Name, Email, Enrollmentyear)
ii. Courses(CourseID, CourseName, Credits)
iii. Registrations(RegistrationID, StudentId, CourseId,
RegistrationdateQuestion).
INTRODUCTION:
Introduction A Course Registration System is essential for managing student enrollments in academic
institutions. This system ensures seamless registration of students for various courses while
maintaining data integrity and consistency. The database schema for this system is designed to
efficiently store and retrieve information related to students, courses, and their respective
registrations. This document outlines the physical schema, logical schema, constraints, and
consistency mechanisms implemented in the database design.

1. Course Registration System – A structured system for managing student enrollments efficiently.

2. Physical Schema – The actual structure of the database, including tables, fields, and data types.

3. Students Table – Stores student details with constraints ensuring valid student records.

4. Courses Table – Holds course information, including credits with specific constraints.
5. Registrations Table – Manages student-course enrollments, ensuring data integrity.

6. Constraints – Enforces data validity through Primary Keys, Foreign Keys, NOT NULL, UNIQUE, and
CHECK constraints.

PHYSICAL SCHEMA:
The database consists of three primary tables: Students, Courses, and Registrations.

1. Students Table
 StudentID (INT, PRIMARY KEY, NOT NULL, UNIQUE)
 Name (VARCHAR(100), NOT NULL)
 Email (VARCHAR(100), NOT NULL, UNIQUE, CHECK (Email LIKE '%@%'))
 EnrollmentYear (INT, NOT NULL, CHECK (EnrollmentYear >= 2000 AND
EnrollmentYear <= YEAR(CURDATE())))
 SQL> desc student;

Name Null? Type

----------------------------------------- -------- ----------------------------

STUDENTID NUMBER(7)

STUDENTNAME VARCHAR2(10)

STUDENTEMAIL VARCHAR2(16)

STUDENTENROLLMENTYEAR NUMBER(7)

2. Courses Table
 CourseID (INT, PRIMARY KEY, NOT NULL, UNIQUE)
 CourseName (VARCHAR(100), NOT NULL)
 Credits (INT, NOT NULL, CHECK (Credits BETWEEN 1 AND 10))
 SQL>desc course;

Name Null? Type

COURSEID NUMBER(7)

COURSENAME VARCHAR2(10)

CREDITS NUMBER(7)

3. Registrations Table
 RegistrationID (INT, PRIMARY KEY, NOT NULL, UNIQUE)
 StudentID (INT, FOREIGN KEY REFERENCES Students(StudentID), NOT NULL)
 CourseID (INT, FOREIGN KEY REFERENCES Courses(CourseID), NOT NULL)
 RegistrationDate (DATE, NOT NULL, CHECK (RegistrationDate <= CURDATE()))
 SQL>desc registration;

Name Null? Type--

REGISTRATIONID NUMBER(10)

STUDENTID NUMBER(7)
COURSEID NUMBER(7)

REGISTRATIONDATE NUMBER(10)

Constraints:
To maintain data integrity, the following constraints have been applied:

1. Primary Key (PK): Ensures unique identification of records in each table (StudentID,
CourseID, RegistrationID).

2. Foreign Key (FK): Enforces referential integrity (StudentID in Registrations references


Students, CourseID in Registrations references Courses).

3. NOT NULL: Ensures essential attributes cannot be left empty.

4. UNIQUE: Prevents duplicate values in StudentID, CourseID, RegistrationID, and Email.

5. CHECK Constraints: Ensures values meet predefined conditions:

Email must have a valid format.

Credits should be between 1 and 10

EnrollmentYear must be within a valid range.

RegistrationDate must not be in the future.

Logical Schema:
The logical schema represents the relationship between tables:

• The Students table stores student details.

• The Courses table contains course information.

• The Registrations table establishes a many-to-many relationship between Students


and Courses, ensuring that each student can register for multiple courses and each course
can have multiple students.

Entity-Relationship (ER) Model:

• Students (1) → (M) Registrations (M) ← (1) Courses

• This indicates that one student can register for multiple courses, and one course can
have multiple students enrolled.

1. Students Table:

insert into student values(7,'prann','[email protected]',2004); 1 row created.

SQL> insert into student values(8,'vedhh','[email protected]',2005); 1 row created.

SQL> insert into student values(9,'chandhh','[email protected]',2006); 1 row created.

SQL> select * from student;

STUDENTID STUDENTNAM STUDENTEMAIL STUDENTENROLLMENTYEAR


7 prann [email protected] 2004

8 vedhh [email protected] 2005

9 chandhh [email protected] 2006

2.Courses Table:

SQL> insert into course values(79,'java',4);

1 row created.

SQL> insert into course

values(78,'dbms',3); 1 row

created.

SQL> insert into course values(76,'python',5);

1 row created.

SQL> select * from course;

COURSEID COURSENAME CREDITS

79 java 4

78 dbms 3

76 python 5

3.Registrations Table:

SQL> insert into Registration

values(189,7,79,1); 1 row created.

SQL> insert into Registration

values(199,8,78,2); 1 row created.

SQL> insert into Registration values(198,9,76,5);

1 row created.

SQL> select * from Registration;

REGISTRATIONID STUDENTID COURSEID REGISTRATIONDATE

189 7 79 1

199 8 78 2

198 9 76 5
Consistency:
To maintain database consistency

1. Referential Integrity: Enforced through foreign key constraints, ensuring that registrations
reference only existing students and courses.

2. Atomicity: Each database operation (such as inserting a registration) must be completed


successfully; otherwise, it is rolled back to prevent partial updates.

3. Isolation: Concurrent transactions do not interfere, ensuring a student’s registration process


is isolated from others.

4. Durability: Once a transaction (e.g., registering a student for a course) is committed, it


remains in the system even in case of failures.

Conclusion:
Conclusion The database schema for the Course Registration System is designed to be efficient,
scalable, and secure while ensuring data integrity and consistency. The application of primary keys,
foreign keys, NOT NULL constraints, UNIQUE constraints, and CHECK constraints ensures that the
data remains valid and reliable. By following best database design practices, this system provides a
robust foundation for student course registrations in any academic institution.

3. Design a relational database schema for an online shopping


system based on the following entities: Users, products, orders,
order details, and reviews. Identify primary and foreign keys and
enforce integrity constraints.
Introduction:
In the modern era of e-commerce, an efficient and well-structured database is essential for
managing online shopping systems. This document presents the relational database schema for an
Online Shopping System, ensuring data integrity and optimized operations. The system consists of
five main entities: Users, Products, Orders, Order Details, and Reviews. The design enforces integrity
constraints through the use of primary and foreign keys, ensuring referential integrity across the
database.

Physical Schema:
Users table:

Create table Users (Userid int primary key, name varchar2(10) not null, email varchar2(30) unique
not null, password varchar2(10) not null, address varchar2(30), phone varchar2(20));

desc users;
Name Null? Type

----------------------------------------- -------- ----------------------------

USERID NOT NULL NUMBER(38)

NAME NOT NULL VARCHAR2(10)

EMAIL NOT NULL VARCHAR2(30)

PASSWORD NOT NULL VARCHAR2(10)

ADDRESS VARCHAR2(30)

PHONE VARCHAR2(10)

Product table:

Create table Products ( ProductID int primary key, name varchar2(15) not null, description
varchar2(15), price number(10,2) not null, stock int not null, category varchar2(10));

desc products;

Name Null? Type

----------------------------------------- -------- ----------------------------

PRODUCTID NOT NULL NUMBER(38)

NAME NOT NULL VARCHAR2(15)

DESCRIPTION VARCHAR2(15)

PRICE NOT NULL NUMBER(10,2)

STOCK NOT NULL NUMBER(38)

CATEGORY VARCHAR2(10)

Orders table:

Create table Orders (OrderID int primary key, UserID int not null, OrderDate timestamp default
current_timestamp, TotalAmount number(10,2) NOT NULL, Status varchar2(20) check (Status IN
('Pending', 'Shipped', 'Delivered', 'Cancelled'))default 'Pending', foreign key (UserID) references
Users(UserID));

desc orders;

Name Null? Type

----------------------------------------- -------- ----------------------------

ORDERID NOT NULL NUMBER(38)

USERID NOT NULL NUMBER(38)

ORDERDATE TIMESTAMP(6)

TOTALAMOUNT NOT NULL NUMBER(10,2)


STATUS VARCHAR2(20)

OrderDetails table:

create table OrderDetails ( OrderDetailID int primary key, orderID int not null, productID int not null,
quantity int not null, subtotal number(10,2)not null, foreign key (OrderID) reference Orders(OrderID),
foreign key (ProductID)references Products(ProductID));

desc orderdetails;

Name Null? Type

----------------------------------------- -------- ----------------------------

ORDERDETAILID NOT NULL NUMBER(38)

ORDERID NOT NULL NUMBER(38)

PRODUCTID NOT NULL NUMBER(38)

QUANTITY NOT NULL NUMBER(38)

PRICE NOT NULL NUMBER(10,2)

SUBTOTAL NOT NULL NUMBER(10,5)

Review table:

create table Reviews ( ReviewID int primary key, UserID int not null, ProductID int not null, Rating int
check (Rating BETWEEN 1 AND 5) not null, comment varchar2(30), ReviewDate timestamp default
current_timestamp, foreign key (UserID) references Users(UserID), foreign key (ProductID) references
Products(ProductID));

desc reviews;

Name Null? Type

----------------------------------- ------ -------- ----------------------------

REVIEWID NOT NULL NUMBER(38)

USERID NOT NULL NUMBER(38)

PRODUCTID NOT NULL NUMBER(38)

RATING NOT NULL NUMBER(38)

Comment VARCHAR2(20)

REVIEWDATE

Logical Schema:
Insert into Users (UserID, Name, Email, Password, Address, Phone) values (1, 'Alice',
'[email protected]', 'pass123', '123 Main St', '9876543210');

1 row created.
Insert into Users (UserID, Name, Email, Password, Address, Phone) values (2, 'Bob',
'[email protected]', 'secure456', '456 Elm St', '8765432109');

1 row created.

Insert into Products (ProductID, Name, Description, Price, Stock, Category) values (101, 'Laptop',
'Gaming Laptop', 2000.50, 10, 'Electronic');

1 row created.

Insert into Products (ProductID, Name, Description, Price, Stock, Category) values(102, 'Phone',
'Smartphone', 50000, 20, 'Electronic');

1 row created.

Insert into Orders (OrderID, UserID, OrderDate, TotalAmount, Status) values(1001, 1,


CURRENT_TIMESTAMP, 1200.50, 'Pending');

1 row created.

Insert into Orders (OrderID, UserID, OrderDate, TotalAmount, Status) values(1002, 2,


CURRENT_TIMESTAMP, 699.99, 'Shipped');

1 row created.

Insert into OrderDetails (OrderDetailID, OrderID, ProductID, Quantity, Price)values (2001, 1001, 101,
1, 1200.50);

1 row created.

Insert into OrderDetails (OrderDetailID, OrderID, ProductID, Quantity, Price) values (2002, 1002,
102, 1, 699.99);

1 row created.

Insert into Reviews (ReviewID, UserID, ProductID, Rating, “comment”, ReviewDate) values(3001, 1,
101, 5, 'Great product!', CURRENT_TIMESTAMP);

1 row created.

Insert into Reviews (ReviewID, UserID, ProductID, Rating,”comment”, ReviewDate) values (3002, 2,
102, 4, 'Good value.', CURRENT_TIMESTAMP);

1 row created.

Expected Output:
Select *from users;
USERID NAME EMAIL PASSWORD ADDRESS PHONE
--------- --------------- --------------------- ---------- -------------------------- ---------
1 Alice [email protected] pass123 Hyderabad 9876543210
2 Bob bob@gmail .com secure456 Suryapet 8765432109
Select *from products;
PRODUCTID NAME DESCRIPTION PRICE STOCK CATEGORY
---------- --------------- --------------- ---------- ---------- ----------
101 laptop gamming 20000 8 electronic
102 iphone smartphone 50000 8 electronic
Select *from Orders;
ORDERID USERID ORDERDATE TOTALAMOUNT STATUS
------------- ----------- ----------------- ------------------- -----------
1001 1 23-FEB-25 20000 Pending
1002 2 23-FEB-25 50000 Shipped
Select *from OrderDetails;
ORDERDETAILID ORDERID PRODUCTID QUANTITY PRICE SUBTOTAL
------------- ---------- ---------- ---------- ---------- ----------
2001 1001 101 1 1200.5 1200.5
2002 1002 102 1 699.99 699.99
Select *from Reviews;
REVIEWID USERID PRODUCTID RATING Comment REVIEWDATE
---------- ---------- ---------- ---------- --------------- ---------------------------
3002 2 102 4 Good value 23-FEB-25 08.31.27.478000 PM
3003 1 101 5 Super 23-FEB-25 08.32.22.806000 PM

Conclusion:
The designed relational database schema provides a well-structured and efficient way to manage an
Online Shopping System. The schema ensures data integrity, minimizes redundancy, and supports
essential e-commerce functionalities. By enforcing constraints, it maintains accuracy and consistency
across all transactions. This design serves as a solid foundation for developing a scalable and reliable
online shopping platform.

4. Design the ER data model for hospital management system and


convert into relational database schema based on the following
entities: parents ,doctors, appointments ,medical records and
resources.
Introduction:
A Hospital Management System (HMS) helps streamline hospital operations by managing patient
records, doctor schedules, appointments, and medical resources efficiently. It reduces paperwork,
improves accuracy, and ensures smooth coordination between different entities.

This document outlines the database structure, including the physical schema, integrity constraints,
logical schema, and consistency mechanisms, to maintain a reliable and efficient system.

 Patients – Stores patient details like name, date of birth, contact information, and medical
history.
 Doctors – Manages doctor information, including specialization, schedules, and contact
details.
 Appointments – Tracks patient-doctor appointments with date, time, and status.
 Medical Records – Stores patient diagnoses, prescriptions, and treatment history.
 Resources – Maintains information about hospital equipment, beds, and other medical
assets.
 Database Schema – Defines how data is stored, structured, and related across tables.
 Integrity Constraints – Ensures data accuracy using primary keys, foreign keys, and validation
rules.
 Logical Schema – Represents relationships between entities like one-to-many (1:M) and
many-to-many (M:N).
 Consistency – Maintains reliable data through ACID properties (Atomicity, Consistency,
Isolation, Durability).

2.Integrity Constraints in the Hospital Management System:


To maintain data accuracy, reliability, and consistency, the following integrity constraints are applied:
 Primary Key Constraints – Ensures each record is uniquely identified in every table (e.g.,
PatientID in the Patient table).
 Foreign Key Constraints – Maintains relationships between tables and enforces referential
integrity (e.g., DoctorID in Appointment refers to DoctorID in the Doctor table).
 Not Null Constraints – Prevents critical fields from being left empty (e.g., PatientName and
AppointmentDate cannot be NULL).
 Unique Constraints – Ensures that specific values do not duplicate (e.g., email and phone
number must be unique for doctors and patients).
 Check Constraints – Enforces data validity (e.g., appointment dates cannot be in the past,
and age must be within a reasonable range).
 Default Constraints – Assigns default values to fields when no input is provided (e.g., Status
in Appointment defaults to "Scheduled").

3.Physical Schema of the Hospital Management System:


The physical schema defines how the data is stored in tables along with their relationships and
constraints. Below is the SQL representation of the Hospital Management System database:
CREATE TABLE Patient (
PatientID NUMBER(5) PRIMARY KEY,
Name VARCHAR2(10) NOT NULL,
DOB VARCHAR2(15) NOT NULL,
Phone VARCHAR2(10) UNIQUE NOT NULL,
Email VARCHAR2(20) UNIQUE NOT NULL
);

CREATE TABLE Doctor (


DoctorID NUMBER(5) PRIMARY KEY,
Name VARCHAR2(10) NOT NULL,
Specialization VARCHAR2(20) NOT NULL,
Phone VARCHAR2(10) UNIQUE NOT NULL
);

CREATE TABLE Appointment (


AppointmentID NUMBER(5) PRIMARY KEY,
PatientID NUMBER(5) NOT NULL,
DoctorID NUMBER(5) NOT NULL,
AppointmentDate VARCHAR2(15) NOT NULL,
Status VARCHAR2(10) DEFAULT 'Scheduled',
FOREIGN KEY (PatientID) REFERENCES Patient(PatientID) ON DELETE CASCADE,
FOREIGN KEY (DoctorID) REFERENCES Doctor(DoctorID) ON DELETE CASCADE
);

CREATE TABLE MedicalRecord (


RecordID NUMBER(5) PRIMARY KEY,
PatientID NUMBER(5) NOT NULL,
Diagnosis VARCHAR2(20) NOT NULL,
Prescription VARCHAR2(20) NOT NULL,
DateOfEntry VARCHAR2(15) DEFAULT TO_CHAR(SYSDATE, 'YYYY-MM-DD'),
FOREIGN KEY (PatientID) REFERENCES Patient(PatientID) ON DELETE CASCADE
);

CREATE TABLE HospitalResource (


ResourceID NUMBER(5) PRIMARY KEY,
ResourceName VARCHAR2(20) NOT NULL,
AvailabilityStatus VARCHAR2(20) DEFAULT 'Available'
);
SOME EXAMPLES OF PHYSICAL SCHEMA:

SQL> DESC PATIENT;


Name Null? Type
----------------------------------------- -------- ----------------------------
PATIENTID NOT NULL NUMBER(5)
NAME NOT NULL VARCHAR2(10)
DOB NOT NULL VARCHAR2(15)
PHONE NOT NULL VARCHAR2(10)
EMAIL NOT NULL VARCHAR2(20)

SQL> DESC DOCTOR;


Name Null? Type
----------------------------------------- -------- ----------------------------
DOCTORID NOT NULL NUMBER(5)
NAME NOT NULL VARCHAR2(10)
SPECIALIZATION NOT NULL VARCHAR2(20)
PHONE NOT NULL VARCHAR2(10)

4.Logical Schema Representation:


Here’s an ER-style representation of relationships:
 Patient (PatientID) → (1:M) Appointment (AppointmentID, DoctorID) → Doctor (DoctorID)
 Patient (PatientID) → (1:M) Medical Record (RecordID, DoctorID) → Doctor (DoctorID)
 Patient (PatientID) → (M:N) Resource (ResourceID)
This logical schema ensures a structured and efficient hospital database, allowing easy data retrieval
and management.

SOME EXAMPLES OF LOGICAL SCHEMA:

SQL> INSERT INTO Patient (PatientID, Name, DOB, Phone, Email)


2 VALUES (1, 'Alice', '1990-05-15', '9876543210', '[email protected]');
1 row created.

SQL> INSERT INTO Patient (PatientID, Name, DOB, Phone, Email)


2 VALUES (2, 'chand', '2006-10-22', '9123456789', '[email protected]');
1 row created.

SQL> select * from patient;

PATIENTID NAME DOB PHONE EMAIL


------------------------------------------------------------------------------------------------
1 Alice 1990-05-15 9876543210 [email protected]
2 chand 2006-10-22 9123456789 [email protected]

SQL> INSERT INTO Doctor (DoctorID, Name, Specialization, Phone)


2 VALUES (1, 'Dr. Pran', 'Cardiology', '9112233445');
1 row created.

SQL> INSERT INTO Doctor (DoctorID, Name, Specialization, Phone)


2 VALUES (2, 'Dr. Shrey', 'Neurology', '9001122334');
1 row created.

SQL> SELECT * FROM DOCTOR;

DOCTORID NAME SPECIALIZATION PHONE


----------------------------------------------------------------------
1 Dr. Pran Cardiology 9112233445
2 Dr. Shrey Neurology 9001122334

5.Consistency:
Consistency is maintained in the system through transaction management and constraints. The
database follows ACID properties:
Atomicity: Ensures transactions are either fully completed or rolled back.
Consistency: Data always remains in a valid state.
Isolation: Ensures multiple transactions do not interfere with each other.
Durability: Data is permanently saved after a transaction is committed.

Expected Output:
Patient Table:
PATIENTID NAME DOB PHONE EMAIL
------------------------------------------------------------------------------------------------
1 Alice 1990-05-15 9876543210 [email protected]
2 chand 2006-10-22 9123456789 [email protected]
------------------------------------------------------------------------------------------------
Doctor Table:
DOCTORID NAME SPECIALIZATION PHONE
--------------------------------------------------------------------------
1 Dr. Pran Cardiology 9112233445
2 Dr. Shrey Neurology 9001122334
--------------------------------------------------------------------------
Appointment Table:
APPOINTMENTID PATIENTID DOCTORID APPOINTMENTDATE STATUS
-------------------------------------------------------------------------------------------------
1 1 1 2025-03-10 Scheduled
2 2 2 2025-03-12 Completed
-----------------------------------------------------------------------------------------
MedicalRecord Table:
RECORDID PATIENTID DIAGNOSIS PRESCRIPTION DATEOFENTRY
------------------------------------------------------------------------------------------------------------------
1 1 Hypertension Medicine A 2025-02-23
2 2 Migraine Medicine B 2025-02-23
HospitalResource Table:
RESOURCEID RESOURCENAME AVAILABILITYSTATUS
--------------------------------------------------------------------------------
1 MRI Scanner Available
2 X-Ray Machine In Use
Conclusion:
The Hospital Management System efficiently organizes patient records, doctor schedules,
appointments, and resources. It ensures data integrity, security, and accessibility, improving hospital
operations and patient care.

5. Solve the following queries using relational algebra and relational


calculus (TRC&DRC) consider the following tables.
Products- ProductID(PK), ProductName (Not Null), Price(Check
constraint value>0).
Customers - CustomerID(PK), Name(Not Null), Email(Unique
constraint to avoid duplication), Address.
Orders - OrderID (PK), CustomerID (FK), ProductID (FK),Quantity
(check constraint to ensure values>0),OrderDate varchar2(10) not
null);
1.Find customers who purchased products costing more than
Rs.1000.
2.Retrieve product names and quantities ordered by a specific
customer named “Alice”.
3.Retrieve all orders placed for products in the “Clothing” category.
4.List the names of customers who ordered at least 5 units of any
product.

Introduction:
Relational algebra and relational calculus are formal query languages used to retrieve data from
relational databases. Relational algebra is procedural, specifying how to retrieve data, while
relational calculus is declarative, specifying what data to retrieve. Tuple Relational Calculus (TRC) and
Domain Relational Calculus (DRC) are two forms of relational calculus. In this solution, we will solve
the given queries using both relational algebra and relational calculus (TRC & DRC). The database
schema consists of three tables: Products, Customers, and Orders. We will also discuss the physical
schema, constraints, logical schema, consistency, and conclusion.

PHYSICAL SCHEMA:
1. Product Table
This table contains information about the products.
1. Product Table
Sql code:
CREATE TABLE product ( productID number PRIMARY KEY, productName VARCHAR2(255) NOT NULL,
price DECIMAL(10, 2) CHECK (price >= 0) ,Category varchar2(15));
SQL> desc product;

Name Null? Type


-------------------- ------------ ----------------------------
PRODUCTID NOT NULL NUMBER(10)
PRODUCTNAME NOT NULL VARCHAR2(30)
PRICE NUMBER(10,2)
CATEGORY VARCHAR2(15)
2. Customers Table
create table customers(CustomerID number(10)primary key,Name varchar2(30) not null,Email
varchar2(30) unique, Address varchar2(30));
SQL> desc customers;
Name Null? Type
-------------------------- -------- ----------------------------
CUSTOMERID NOT NULL NUMBER(10)
NAME NOT NULL VARCHAR2(30)
EMAIL VARCHAR2(30)
ADDRESS VARCHAR2(30)
3.Order1 Table
create table Orders(OrderID number(10) primary key,CustomerID number(10), ProductID
number(10),Quantity number(5) CHECK (Quantity > 0), orderdate varchar2(10) not null);
SQL> desc order1;
Name Null? Type
----------------------------------- -------- ----------------------------
ORDERID NOT NULL NUMBER(10)
CUSTOMERID NUMBER(10)
PRODUCTID NUMBER(10)
QUANTITY NUMBER(5)
ORDERDATE NOT NULL VARCHAR2(10)

LOGICAL SCHEMA:
Insert into Products:
SQL> insert into product values(101,'vivo',12000, 'Electronics');
1 row created.
SQL> insert into product values(102,'shirt',5000,’clothing’);
1 row created.
SQL> insert into product values(104,'laptop',65000, 'Electronics');
1 row created.
SQL> select * from product;
PRODUCTID PRODUCTNAME PRICE CATEGORY
---------- ------------------------------ ---------- --------------
101 vivo 12000 Electronics
102 shirt 5000 clothing
103 redmi 20000 Electronics
104 laptop 25000 Electronics
105 oppo 15000 Electronics
Insert into Customers:
SQL> insert into customers values(501,'Alice','[email protected]','hyd');

1 row created.
SQL> insert into customers values(502,'BBB','[email protected]','adilabad');
1 row created.
SQL> insert into customers values(503,'CCC','[email protected]','hayathnagar');
1 row created.
Output:
CUSTOMERID NAME EMAIL ADDRESS
---------- ---------- --------------- ----------
501 Alice [email protected] Hyd
502 BBB [email protected] Adilabad
503 CCC [email protected] Hayathnagar
Insert into Orders
SQL> insert into order1 values(1001,501,101,5,'15-01-2024');
1 row created.
SQL> insert into order1 values(1002,502,102,2,'25-01-2024');
1 row created.
SQL> insert into order1 values(1003,503,103,6,'5-01-2024');
1 row created.
Output:
ORDERID CUSTOMERID PRODUCTID QUANTITY ORDERDATE
---------- ---------- ---------- ---------- ----------
1001 501 101 5 15-01-2024
1002 502 102 2 25-01-2024
1003 503 103 6 5-01-2024
1004 504 104 3 14-01-2024
1005 505 105 4 10-02-2024

CONSISTENCY:
i. Find the customers who purchased products costing more than Rs. 1000
SQL Query:
SELECT DISTINCT c.name from customers c join order1 o on c.customerID = o.customerID join
product p on o.productId = p.productId where p.price > 1000;
Output:
NAME
------------------------------
BBB
Alice
CCC
EEE
DDD
ii. Retrieve product names and quantities ordered by a specific customer named "Alice"
SQL Query:
SELECT p.productName, o.quantity FROM order1 o JOIN product p ON o.productID = p.productID
JOIN customers c ON o.customerID = c.customerID WHERE c.name = 'Alice';
Output:
iii. Retrieve all orders placed for products in the "Clothing" category
SQL Query:
SELECT o.orderID, o.customerID, o.productID, o.quantity, o.orderdate FROM order1 o JOIN product p
ON o.productID = p.productID WHERE p.productname = 'clothing';
Output:
OrderID CustomerID ProductID Quantity OrderDate
--------- ------------ ------------ --------- ------------
1002 101 102 2 25-01-2024
iv. List the names of customers who ordered at least 5 units of any product
SQL Query:
SELECT DISTINCT c.name FROM customers c JOIN order1 o ON c.customerID = o.customerID WHERE
o.quantity >= 5;
PRODUCTNAME QUANTITY
-------------------------- ----------
vivo 5
OUTPUT:
NAME
------------------------------
Alice
CCC

Conclusion:
In this database system, we successfully created and populated tables for Products, Customers, and
Orders to store structured data. We then executed four SQL queries to extract relevant information,
demonstrating how relational database operations can be used to retrieve insights from data.This
project showcases the power of SQL queries in managing relational databases and extracting
valuable business insights, which can be applied in real-world e-commerce and inventory
management systems.

You might also like