A scenario-based Hospital Management System developed using MySQL to demonstrate relational database design, SQL programming, stored procedures, stored functions, triggers, transaction management, exception handling, error logging, billing, payments, room allocation, and complete patient workflow management.
The project is designed around a fictional CarePlus Hospital and implements an end-to-end patient workflow, from patient registration and appointment booking to admission, room allocation, billing, payment, and discharge.
- Project Overview
- Objectives
- Hospital Scenario
- Database Architecture
- Database Entities
- Key Relationships
- Technologies Used
- Project Structure
- SQL Features Implemented
- Variables and Operators
- Conditional Logic
- Loops
- Stored Procedures
- Stored Functions
- Triggers
- Billing and Payment Workflow
- Transaction Control
- Exception Handling
- Error Logging
- Required Test Cases
- Rahul Sharma Integrated Workflow
- Final Output
- Expected Final Output
- Submission Requirements
- How to Run
- Learning Outcomes
- Submission Checklist
- Project Highlights
- Author
The Hospital Management System is a relational database project created to manage core hospital operations using MySQL.
The system handles:
- Patient registration
- Department management
- Doctor management
- Appointment booking
- Room allocation
- Patient admissions
- Billing
- Payments
- Patient discharge
- Error logging
- Transaction management
The project goes beyond basic CRUD operations by implementing MySQL programming features to enforce hospital-specific business rules and automate dependent database operations.
It demonstrates how SQL can be used to solve practical business problems rather than simply creating isolated SQL examples.
The main objectives of this project are to:
- Design a relational hospital database.
- Create appropriate tables, primary keys, and foreign keys.
- Insert realistic hospital sample data.
- Apply constraints to prevent invalid data.
- Use variables and SQL operators for calculations and conditions.
- Implement conditional logic using
IF,ELSEIF, andELSE. - Implement loops for repetitive hospital operations.
- Develop reusable stored procedures.
- Develop reusable stored functions.
- Automate database updates using triggers.
- Demonstrate
COMMIT,ROLLBACK,SAVEPOINT, andRELEASE SAVEPOINT. - Implement exception handling using MySQL handlers.
- Use
SIGNALfor business-rule validation. - Use
GET DIAGNOSTICSto capture SQL error information. - Maintain an
Error_Logtable for failed operations. - Test valid and invalid hospital operations.
- Demonstrate a complete patient workflow using Rahul Sharma.
The project is based on a fictional hospital named CarePlus Hospital.
The hospital requires a database system to manage:
- Patients
- Departments
- Doctors
- Appointments
- Rooms
- Admissions
- Bills
- Payments
- Errors
The system also prevents invalid operations. Examples include:
- A patient cannot be registered with a duplicate phone number.
- An appointment cannot be booked for a non-existing patient.
- An appointment cannot be booked for a non-existing doctor.
- An occupied room cannot be allocated again.
- A payment cannot exceed the outstanding bill amount.
- Invalid business operations generate controlled errors.
- Successful payments automatically update bill payment status.
- Patient discharge automatically makes the assigned room available.
- Errors generated during procedure execution are recorded in
Error_Log.
The database used in this project is:
HospitalManagementDB
The database contains the following main entities:
Departments
Patients
Doctors
Appointments
Rooms
Admissions
Bills
Payments
Error_Log
The database follows a relational structure using:
- Primary Keys
- Foreign Keys
- Unique Constraints
- Not Null Constraints
- Check Constraints
- Default Values
- Relationships between entities
Stores hospital department information.
Examples: Cardiology, Emergency, Pediatrics, General Medicine.
Main information: Department ID, Department Name, Location, Creation Date.
Stores patient information.
Main information: Patient ID, First Name, Last Name, Date of Birth, Gender, Phone, Email, Address, Patient Condition, Registration Date.
The table uses constraints to prevent duplicate contact information and invalid data.
Stores doctor information.
Main information: Doctor ID, Doctor Name, Specialization, Department, Phone, Consultation Fee.
Doctors are linked to departments using a foreign key.
Manages patient appointments.
Main information: Appointment ID, Patient ID, Doctor ID, Appointment Date, Appointment Type, Priority, Status, Notes, Creation Date.
- Appointment types: Regular, Emergency, Follow-up
- Appointment status: Scheduled, Completed, Cancelled
Manages hospital rooms.
Main information: Room ID, Room Number, Room Type, Daily Charge, Availability.
- Room types: General, Semi-Private, Private, ICU
- Availability: Available, Occupied
Manages inpatient admissions.
Main information: Admission ID, Patient ID, Room ID, Admission Date, Discharge Date, Diagnosis, Admission Status.
- Admission status: Admitted, Discharged
Manages patient billing.
Main information: Bill ID, Patient ID, Admission ID, Consultation Charge, Room Charge, Medicine Charge, Other Charge, Subtotal, Discount, Tax, Total Amount, Payment Status, Bill Date.
- Payment status: Pending, Partially Paid, Paid
Stores payment transactions.
Main information: Payment ID, Bill ID, Payment Date, Amount, Payment Method, Payment Status.
- Payment methods: Cash, Card, UPI, Online
- Payment status: Successful, Failed
Stores errors generated during stored procedure execution.
It records: Error ID, Error Time, Procedure Name, Error Message, Related Identifier.
This provides a centralized mechanism for tracking failed operations.
The database uses primary keys and foreign keys to establish relationships between entities.
Departments
โ
โผ
Doctors
โ
โผ
Appointments
โฒ
โ
Patients
โ โ
โโโโโโโโโโโ โโโโโโโโโโโโ
โผ โผ
Admissions Bills
โ โ
โผ โผ
Rooms Payments
| Parent | Child |
|---|---|
| Departments | Doctors |
| Patients | Appointments |
| Doctors | Appointments |
| Patients | Admissions |
| Rooms | Admissions |
| Patients | Bills |
| Admissions | Bills |
| Bills | Payments |
| Category | Tool |
|---|---|
| Database | MySQL |
| Language | SQL |
| Database Client | MySQL Workbench |
| Version Control | Git |
| Repository Hosting | GitHub |
The project is organized into separate SQL files according to the different sections and requirements.
Hospital-Management-System/
โ
โโโ README.md
โ
โโโ 01_Database_and_Tables.sql
โโโ 02_Sample_Data.sql
โโโ 03_Variables_and_Operators.sql
โโโ 04_IF_ELSE_Decisions.sql
โโโ 05_Loops.sql
โโโ 06_Stored_Procedures.sql
โโโ 07_Stored_Functions.sql
โโโ 08_Triggers.sql
โโโ 09_Transactions_TCL.sql
โโโ 10_Exception_Handling.sql
โโโ 11_Required_Test_Cases.sql
โโโ 12_Final_Rahul_Workflow.sql
| File | Description |
|---|---|
01_Database_and_Tables.sql |
Creates the database and all required tables |
02_Sample_Data.sql |
Inserts realistic hospital sample data |
03_Variables_and_Operators.sql |
Demonstrates variables and SQL operators |
04_IF_ELSE_Decisions.sql |
Implements hospital decision-making using conditional logic |
05_Loops.sql |
Implements WHILE, LOOP/CURSOR, and REPEAT operations |
06_Stored_Procedures.sql |
Contains hospital management stored procedures |
07_Stored_Functions.sql |
Contains reusable stored functions and test SELECT queries |
08_Triggers.sql |
Creates and tests automatic database triggers |
09_Transactions_TCL.sql |
Demonstrates COMMIT, ROLLBACK, SAVEPOINT, and RELEASE SAVEPOINT |
10_Exception_Handling.sql |
Demonstrates exception handling and Error_Log |
11_Required_Test_Cases.sql |
Contains the required 15 test cases |
12_Final_Rahul_Workflow.sql |
Demonstrates the complete Rahul Sharma hospital workflow |
| Feature | Implementation |
|---|---|
| Database Design | Relational Hospital Database |
| Primary Keys | Implemented |
| Foreign Keys | Implemented |
| Constraints | PK, FK, UNIQUE, NOT NULL, CHECK |
| Sample Data | Patients, doctors, departments, rooms, appointments, admissions, bills, payments |
| Variables | Session and local variables |
| Operators | Arithmetic, comparison, logical |
| Conditional Logic | IF / ELSEIF / ELSE |
| Business Validation | SIGNAL |
| Loops | WHILE, LOOP, REPEAT |
| Stored Procedures | 5+ |
| Stored Functions | 3+ |
| Triggers | 3+ |
| Transactions | COMMIT / ROLLBACK |
| Savepoints | SAVEPOINT / ROLLBACK TO SAVEPOINT / RELEASE SAVEPOINT |
| Exception Handling | SQLEXCEPTION handlers |
| Diagnostics | GET DIAGNOSTICS |
| Error Logging | Error_Log |
| Testing | 15 required test cases |
| Integrated Workflow | Rahul Sharma |
Variables are used for hospital-related calculations such as consultation charges, room charges, medicine charges, other charges, subtotal, discount, tax, and final bill amount.
@consultation_fee
@room_charge
@medicine_charge
@other_charge
@tax_rate
@discount_rateLocal variables are used inside stored procedures for temporary calculations and business-rule processing.
+ - * /
Used for adding charges, calculating discounts, calculating taxes, and calculating final bill amounts.
= > < >= <= <>
Used for comparing payments and balances, checking patient conditions, checking room availability, and validating dates.
AND OR NOT
Used to combine multiple hospital business conditions.
The project uses IF, ELSEIF, and ELSE to implement actual hospital decision-making.
Age < 18 โ Child
Age 18โ59 โ Adult
Age >= 60 โ Senior
Priority is determined using appointment type and patient condition.
Emergency condition โ Emergency Priority
Critical condition โ Emergency Priority
Serious condition โ High Priority
Follow-up โ Normal Priority
Other โ Low Priority
No successful payment โ Pending
Partial payment โ Partially Paid
Full payment โ Paid
Room allocation checks:
- Whether the patient exists
- Whether the room exists
- Whether the room is available
- Whether the patient already has an active admission
- Whether ICU requirements are satisfied
Business-rule violations are raised using SIGNAL SQLSTATE '45000'.
The project implements multiple loops for repetitive hospital operations.
Used to generate appointment records for multiple days.
Start Date โ Day 1 Appointment โ Day 2 Appointment โ Day 3 Appointment โ ...
The loop uses a counter to control the number of generated appointments.
Used to process unpaid bills.
Read unpaid bill
โ
Calculate successful payments
โ
Calculate outstanding balance
โ
Classify bill
โ
Read next bill
โ
Repeat
Used for repeated reminder-generation operations.
The project therefore demonstrates more than the required two loops.
The project implements more than the required five stored procedures.
Registers a new patient after validating patient information, duplicate phone number, duplicate email, and date of birth. Includes exception handling and error logging.
Books an appointment after checking patient existence, doctor existence, appointment date, doctor scheduling conflicts, and appointment priority.
Processes patient payments and validates bill existence, positive payment amount, outstanding balance, and overpayment prevention. Also updates the bill payment status.
Generates a patient bill using consultation charges, room charges, medicine charges, other charges, discount, tax, and final amount.
Allocates an available room to an admitted patient after checking patient existence, room existence, room availability, existing admission, and ICU suitability.
The project implements reusable stored functions for common hospital calculations.
Calculates the patient's age from the date of birth.
SELECT CalculateAge('2000-05-15') AS Age;Classifies a patient as Child, Adult, or Senior.
SELECT GetPatientCategory('2000-05-15') AS Patient_Category;Calculates the outstanding balance of a bill.
SELECT CalculateBillBalance(1) AS Outstanding_Balance;Calculates the number of days a patient stayed in the hospital.
SELECT CalculateLengthOfStay(1) AS Length_Of_Stay;Each function includes test SELECT statements in the corresponding SQL file.
The project implements three major triggers to automate dependent database updates.
After a successful payment is inserted, the trigger recalculates the successful payment total and updates the bill status.
Payment Inserted
โ
Successful Payment
โ
Calculate Total Paid
โ
Compare with Bill
โ
Update Bill Status (Pending / Partially Paid / Paid)
When a patient admission is inserted, the assigned room is automatically marked Occupied.
When an admission is updated from Admitted to Discharged, the assigned room automatically becomes Available.
These triggers automate dependent updates and reduce manual database operations.
Consultation Charges
+
Room Charges
+
Medicine Charges
+
Other Charges
โ
Subtotal
โ
Discount
โ
Tax
โ
Final Amount
โ
Payment
โ
Pending / Partially Paid / Paid
Every payment is validated against the outstanding bill balance.
Bill Generated โ Pending โ Partial Payment โ Partially Paid
โ Remaining Payment โ Paid โ Outstanding Balance = 0
The project demonstrates MySQL Transaction Control Language (TCL).
Implemented commands:
START TRANSACTION;
COMMIT;
ROLLBACK;
SAVEPOINT savepoint_name;
ROLLBACK TO SAVEPOINT savepoint_name;
RELEASE SAVEPOINT savepoint_name;| Command | Purpose |
|---|---|
COMMIT |
Permanently saves successful database operations |
ROLLBACK |
Undoes database changes when a transaction fails |
SAVEPOINT |
Creates a checkpoint inside a transaction |
ROLLBACK TO SAVEPOINT |
Undoes only the operations performed after a savepoint, keeping earlier changes |
RELEASE SAVEPOINT |
Removes a savepoint when it is no longer required |
Stored procedures include exception handlers using:
DECLARE EXIT HANDLER FOR SQLEXCEPTIONSQL error information is captured using:
GET DIAGNOSTICS CONDITION 1The captured information is stored in the Error_Log table.
Business-rule violations are raised using:
SIGNAL SQLSTATE '45000'Examples include:
- Invalid payment amount
- Payment greater than outstanding balance
- Non-existing patient
- Non-existing doctor
- Non-existing room
- Occupied room allocation
- Invalid business conditions
The Error_Log table provides a centralized record of procedure failures.
Stored information: Error ID, Error Time, Procedure Name, Error Message, Related Identifier.
Procedure Execution
โ
Error Occurs
โ
Exception Handler
โ
GET DIAGNOSTICS
โ
Error_Log
This allows failed operations to be reviewed and diagnosed.
The project includes all 15 required test cases.
| # | Test Case | Expected Result |
|---|---|---|
| 1 | Register a new patient successfully | Patient registered |
| 2 | Attempt duplicate patient registration | Validation/error generated |
| 3 | Book a valid appointment | Appointment created |
| 4 | Book appointment for non-existing patient/doctor | Operation rejected |
| 5 | Allocate an available room | Room allocated and marked occupied |
| 6 | Attempt to allocate an occupied room | Allocation rejected |
| 7 | Generate a bill | Charges calculated correctly |
| 8 | Process a valid partial payment | Bill becomes partially paid |
| 9 | Attempt payment greater than outstanding balance | Payment rejected |
| 10 | Complete remaining payment | Bill becomes fully paid |
| 11 | Discharge patient | Room becomes available |
| 12 | Force a procedure error | Error_Log receives error |
| 13 | Execute successful transaction | COMMIT verified |
| 14 | Execute failed transaction | ROLLBACK verified |
| 15 | Use SAVEPOINT and ROLLBACK TO SAVEPOINT | Partial rollback verified |
The project includes a complete integrated hospital workflow using Rahul Sharma.
Rahul Sharma
โ
Patient Registration
โ
Appointment Booking
โ
Doctor Consultation
โ
Patient Admission
โ
Room Allocation
โ
Bill Generation
โ
Partial Payment
โ
Bill = Partially Paid
โ
Remaining Payment
โ
Bill = Paid
โ
Patient Discharge
โ
Room = Available
- Patient registration
- Appointment booking and completion
- Patient condition update
- Room allocation and admission creation
- Bill generation and balance calculation
- Partial payment with automatic payment-status update
- Remaining payment and final bill settlement
- Patient age/category calculation
- Length-of-stay calculation
- Patient discharge with automatic room availability update
- Final workflow reporting
This scenario demonstrates how all major components of the database work together.
The final SQL queries provide reports showing the completed hospital workflow.
| Report | Details Displayed |
|---|---|
| Patient Information | Patient ID, name, date of birth, patient category, condition |
| Appointment Information | Appointment ID, doctor, date, type, priority, status |
| Admission Information | Admission ID, admission date, discharge date, diagnosis, status |
| Room Information | Room number, room type, availability |
| Billing Information | Bill ID, subtotal, discount, tax, total amount, payment status |
| Payment Information | Payment history, total paid, outstanding balance, payment status |
| Error Information | Error ID, error time, procedure name, error message, related identifier |
The completed project demonstrates the ability to design and implement a relational hospital database and use MySQL programming features to solve real business problems.
The final database:
- Prevents invalid operations where possible.
- Applies meaningful hospital business rules.
- Validates patient, doctor, room, bill, and payment information.
- Automates dependent updates using triggers.
- Calculates bills and outstanding balances.
- Manages patient admissions and room availability.
- Handles successful and failed transactions.
- Recovers safely from failures using transactions.
- Uses savepoints for partial transaction rollback.
- Records useful error information in
Error_Log. - Successfully executes the complete Rahul Sharma workflow.
| Component | Contents |
|---|---|
| Database and Tables | Database creation, table creation, primary keys, foreign keys, constraints |
| Sample Data | Departments, doctors, patients, appointments, rooms, admissions, bills, payments |
| Stored Procedures | Comments explaining parameters, local variables, conditions, loops, exception handlers, business rules |
| Stored Functions | Functions with corresponding test SELECT statements |
| Triggers | Triggers with test INSERT and UPDATE operations |
| TCL Demonstrations | COMMIT, ROLLBACK, SAVEPOINT, ROLLBACK TO SAVEPOINT, RELEASE SAVEPOINT |
| Exception Handling | Exception handlers, GET DIAGNOSTICS, SIGNAL, error logging, Error_Log output |
| Final Workflow | Final SELECT queries showing the completed hospital workflow |
git clone https://github.com/abhijitpavse/Hospital-Management-System.git
cd Hospital-Management-SystemOpen the project SQL files using MySQL Workbench.
Run 01_Database_and_Tables.sql. This creates HospitalManagementDB and all required tables.
Run 02_Sample_Data.sql.
Run 03_Variables_and_Operators.sql and 04_IF_ELSE_Decisions.sql.
Run 05_Loops.sql.
Run 06_Stored_Procedures.sql.
Run 07_Stored_Functions.sql.
Run 08_Triggers.sql.
Run 09_Transactions_TCL.sql.
Run 10_Exception_Handling.sql, then verify generated errors:
SELECT * FROM Error_Log;Run 11_Required_Test_Cases.sql to verify all 15 required test scenarios.
Run 12_Final_Rahul_Workflow.sql.
Run the final SELECT queries to verify Patients, Doctors, Appointments, Admissions, Rooms, Bills, Payments, and Error_Log.
Through this project, the following concepts are demonstrated:
- Relational database design
- Entity relationships
- Primary keys and foreign keys
- Database constraints
- Data validation
- SQL variables
- Arithmetic, comparison, and logical operators
- Conditional statements
- WHILE, LOOP/CURSOR, and REPEAT loops
- Stored procedures
- Stored functions
- Database triggers
- Billing calculations
- Payment validation
- Transaction management (COMMIT, ROLLBACK, SAVEPOINT, ROLLBACK TO SAVEPOINT, RELEASE SAVEPOINT)
- Exception handling (SIGNAL, GET DIAGNOSTICS)
- Error logging
- Business-rule implementation
- End-to-end database testing
- Database and all tables created
- Sample data inserted
- Variables demonstrated
- Operators demonstrated
- IF / ELSEIF / ELSE demonstrated
- At least 2 loops implemented
- At least 5 procedures implemented
- At least 3 functions implemented
- At least 3 triggers implemented
- COMMIT demonstrated
- ROLLBACK demonstrated
- SAVEPOINT demonstrated
- ROLLBACK TO SAVEPOINT demonstrated
- RELEASE SAVEPOINT demonstrated
- Exception handlers implemented
- SIGNAL business validation implemented
- GET DIAGNOSTICS demonstrated
- Error_Log populated during an error test
- 15 required test cases completed
- Rahul Sharma integrated workflow tested
- Final SELECT reports generated
- ๐ฅ Real-world hospital management scenario
- ๐๏ธ Relational MySQL database design
- ๐ Primary and foreign key relationships
- ๐ Data validation and business rules
- โ๏ธ 5+ stored procedures
- ๐งฎ 3+ stored functions
- ๐ 3+ database triggers
- ๐ Multiple SQL loops
- ๐ณ Automated billing and payment tracking
- ๐จ Room and admission management
- ๐จ Exception handling and error logging
- ๐ Transaction and savepoint management
- ๐งช 15 required test cases
- ๐จโโ๏ธ Complete Rahul Sharma patient workflow
- ๐ Final hospital workflow reports
This repository is organized according to the project requirements. The SQL files contain the actual implementation, while this README provides an overview of the database architecture, hospital entities, SQL programming concepts, stored procedures, functions, triggers, transactions, exception handling, error logging, test cases, integrated workflow, and project execution steps.
Sections describing expected output, submission requirements, checklist items, and instructions are documentation and evaluation criteria rather than separate SQL coding modules.
Abhijit Pavse
Computer Science Graduate | Aspiring Data Engineer
Interested in: Data Engineering โข Data Analytics โข SQL โข Python โข Databases โข Artificial Intelligence
- GitHub: github.com/abhijitpavse
- LinkedIn: linkedin.com/in/abhijitpavse
- LeetCode: leetcode.com/u/abhijitpavse
This project was developed as a scenario-based MySQL database project to demonstrate practical implementation of relational database concepts and MySQL programming features in a hospital management environment.
It focuses on using SQL to solve real-world hospital business problems through validation, automation, transaction management, exception handling, and integrated workflow processing.
Feel free to explore the SQL files and review the implementation to learn more about:
MySQL โข SQL โข DBMS โข Stored Procedures โข Stored Functions โข Triggers โข Transactions โข Exception Handling โข Database Design โข Hospital Management Systems