Database Management Systems

Lecture 22: Real-World Database Applications
Instructor: Mohsin Dar | School of Computer Science | UPES
0% Complete
Introduction to Real-World Database Applications

In today's digital age, databases are the backbone of nearly every major system we interact with daily. From online banking to healthcare systems, databases enable structured data storage, retrieval, and processing at an unprecedented scale.

Why This Matters

Understanding how to design and implement database solutions for real-world applications is a critical skill for database professionals. This lecture bridges the gap between theoretical database concepts and practical implementation.

Learning Objectives

Real-World Database Examples

  • Banking & Financial Systems
  • Hospital Management Systems
  • E-commerce Platforms
  • University Management Systems
  • Social Media Networks
  • Government & E-Governance
Key Concepts in Real-World Database Applications

Core Components

Database Project Lifecycle

The systematic approach to designing and implementing a database system:

  1. Requirement Analysis: Understanding business needs
  2. Conceptual Design: Creating ER models
  3. Logical Design: Converting to relational schema
  4. Physical Design: Implementation decisions
  5. Implementation: Creating the database
  6. Testing & Optimization: Ensuring performance
  7. Deployment & Maintenance: Going live and beyond

Business Rules & Data Integrity

Essential for maintaining data quality and consistency:

  • Primary Keys: Uniquely identify records
  • Foreign Keys: Maintain relationships
  • Constraints: Enforce data rules
  • Validation Rules: Ensure data quality

Scalability & Performance

Critical considerations for growing applications:

  • Vertical Scaling: Adding more power to existing hardware
  • Horizontal Scaling: Adding more servers
  • Indexing: For faster searches
  • Partitioning: For better data management
  • Caching: For improved performance
Database Design Process

Step-by-Step Design Approach

1. Problem Identification

Define the real-world scenario and identify stakeholders.

Example: Hospital Management System

Stakeholders: Doctors, Patients, Admin Staff, Pharmacists

Key Requirements: Patient records, Appointments, Billing, Doctor schedules

2. Requirement Analysis

Gather both functional and non-functional requirements.

Key Questions:

  • What data needs to be stored?
  • Who will access the data?
  • What are the performance requirements?
  • What are the security considerations?

3. Conceptual Design (ER Modeling)

Create an Entity-Relationship diagram to represent the data model.

Example Entities:

  • Patient (PatientID, Name, DOB, Contact)
  • Doctor (DoctorID, Name, Specialization)
  • Appointment (AppID, PatientID, DoctorID, Date, Time)

4. Logical Design

Convert the ER model into a relational schema.

                    -- Patient Table
                    CREATE TABLE Patient (
                        PatientID INT PRIMARY KEY,
                        Name VARCHAR(100) NOT NULL,
                        DOB DATE,
                        Contact VARCHAR(50),
                        Address TEXT,
                        InsuranceID VARCHAR(50)
                    );
                    
                    -- Doctor Table
                    CREATE TABLE Doctor (
                        DoctorID INT PRIMARY KEY,
                        Name VARCHAR(100) NOT NULL,
                        Specialization VARCHAR(100),
                        Contact VARCHAR(50),
                        Department VARCHAR(50)
                    );
                    
                    -- Appointment Table
                    CREATE TABLE Appointment (
                        AppID INT PRIMARY KEY,
                        PatientID INT,
                        DoctorID INT,
                        AppDate DATE NOT NULL,
                        AppTime TIME NOT NULL,
                        Status VARCHAR(20) DEFAULT 'Scheduled',
                        FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
                        FOREIGN KEY (DoctorID) REFERENCES Doctor(DoctorID)
                    );
                    

5. Physical Design

Make implementation decisions for performance and scalability.

Key Considerations:

  • Indexing: Create indexes on frequently queried columns
  • Partitioning: For large tables
  • Storage Engines: Choose based on requirements
  • Backup Strategy: Regular backups and recovery plans
Worked Examples

Example 1: Online Shopping Database

Database Schema

                    -- Customer Table
                    CREATE TABLE Customer (
                        CustomerID INT PRIMARY KEY,
                        Name VARCHAR(100) NOT NULL,
                        Email VARCHAR(100) UNIQUE,
                        JoinDate DATE DEFAULT CURRENT_DATE,
                        LastLogin DATETIME
                    );
                    
                    -- Product Table
                    CREATE TABLE Product (
                        ProductID INT PRIMARY KEY,
                        Name VARCHAR(200) NOT NULL,
                        Description TEXT,
                        Price DECIMAL(10,2) NOT NULL,
                        StockQuantity INT DEFAULT 0,
                        CategoryID INT
                    );
                    
                    -- Order Table
                    CREATE TABLE Orders (
                        OrderID INT PRIMARY KEY,
                        CustomerID INT,
                        OrderDate DATETIME DEFAULT CURRENT_TIMESTAMP,
                        Status VARCHAR(50),
                        TotalAmount DECIMAL(12,2),
                        FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID)
                    );
                    
                    -- Order_Item Table
                    CREATE TABLE Order_Item (
                        OrderID INT,
                        ProductID INT,
                        Quantity INT NOT NULL,
                        UnitPrice DECIMAL(10,2) NOT NULL,
                        PRIMARY KEY (OrderID, ProductID),
                        FOREIGN KEY (OrderID) REFERENCES Orders(OrderID),
                        FOREIGN KEY (ProductID) REFERENCES Product(ProductID)
                    );
                    

Key Operations

                    -- Add a new product
                    INSERT INTO Product (ProductID, Name, Description, Price, StockQuantity, CategoryID)
                    VALUES (1, 'Wireless Mouse', 'Ergonomic wireless mouse with 2.4GHz connectivity', 29.99, 100, 5);
                    
                    -- Create a new order
                    INSERT INTO Orders (OrderID, CustomerID, Status, TotalAmount)
                    VALUES (1001, 42, 'Processing', 89.97);
                    
                    -- Add items to order
                    INSERT INTO Order_Item (OrderID, ProductID, Quantity, UnitPrice)
                    VALUES (1001, 1, 3, 29.99);
                    
                    -- Update stock
                    UPDATE Product 
                    SET StockQuantity = StockQuantity - 3 
                    WHERE ProductID = 1;
                    

Example 2: University Management System

Database Schema

                    -- Student Table
                    CREATE TABLE Student (
                        StudentID INT PRIMARY KEY,
                        Name VARCHAR(100) NOT NULL,
                        Email VARCHAR(100) UNIQUE,
                        EnrollmentDate DATE,
                        Program VARCHAR(100)
                    );
                    
                    -- Course Table
                    CREATE TABLE Course (
                        CourseID VARCHAR(20) PRIMARY KEY,
                        Title VARCHAR(200) NOT NULL,
                        Credits INT,
                        DepartmentID INT,
                        Description TEXT
                    );
                    
                    -- Enrollment Table
                    CREATE TABLE Enrollment (
                        EnrollmentID INT PRIMARY KEY,
                        StudentID INT,
                        CourseID VARCHAR(20),
                        Semester VARCHAR(20),
                        Year INT,
                        Grade VARCHAR(2),
                        FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
                        FOREIGN KEY (CourseID) REFERENCES Course(CourseID)
                    );
                    
                    -- Instructor Table
                    CREATE TABLE Instructor (
                        InstructorID INT PRIMARY KEY,
                        Name VARCHAR(100) NOT NULL,
                        DepartmentID INT,
                        Email VARCHAR(100) UNIQUE
                    );
                    
                    -- Course_Section Table
                    CREATE TABLE Course_Section (
                        SectionID INT PRIMARY KEY,
                        CourseID VARCHAR(20),
                        InstructorID INT,
                        Semester VARCHAR(20),
                        Year INT,
                        Room VARCHAR(20),
                        Schedule VARCHAR(100),
                        FOREIGN KEY (CourseID) REFERENCES Course(CourseID),
                        FOREIGN KEY (InstructorID) REFERENCES Instructor(InstructorID)
                    );
                    

Common Queries

                    -- Find all courses a student is enrolled in
                    SELECT c.Title, e.Semester, e.Year, e.Grade
                    FROM Enrollment e
                    JOIN Course c ON e.CourseID = c.CourseID
                    WHERE e.StudentID = 12345
                    ORDER BY e.Year, 
                        CASE e.Semester 
                            WHEN 'Fall' THEN 1 
                            WHEN 'Spring' THEN 2 
                            WHEN 'Summer' THEN 3 
                            ELSE 4 
                        END;
                    
                    -- Get class roster for a course section
                    SELECT s.Name, s.Email
                    FROM Enrollment e
                    JOIN Student s ON e.StudentID = s.StudentID
                    WHERE e.CourseID = 'CS101' 
                    AND e.Semester = 'Fall' 
                    AND e.Year = 2023;
                    
                    -- Calculate student GPA
                    SELECT 
                        s.StudentID,
                        s.Name,
                        ROUND(SUM(
                            CASE 
                                WHEN e.Grade = 'A' THEN 4.0
                                WHEN e.Grade = 'A-' THEN 3.7
                                WHEN e.Grade = 'B+' THEN 3.3
                                WHEN e.Grade = 'B' THEN 3.0
                                WHEN e.Grade = 'B-' THEN 2.7
                                WHEN e.Grade = 'C+' THEN 2.3
                                WHEN e.Grade = 'C' THEN 2.0
                                WHEN e.Grade = 'C-' THEN 1.7
                                WHEN e.Grade = 'D+' THEN 1.3
                                WHEN e.Grade = 'D' THEN 1.0
                                ELSE 0
                            END * c.Credits) / SUM(c.Credits), 2) AS GPA
                    FROM Student s
                    JOIN Enrollment e ON s.StudentID = e.StudentID
                    JOIN Course c ON e.CourseID = c.CourseID
                    WHERE s.StudentID = 12345
                    AND e.Grade IS NOT NULL
                    GROUP BY s.StudentID, s.Name;
                    
Real-World Case Studies

🏥 Hospital Management System

Requirements:

  • Comprehensive patient records management
  • Appointment scheduling
  • Doctor and staff management
  • Pharmacy and inventory management
  • Billing and insurance processing
  • Laboratory test tracking

Challenges:

  • Handling sensitive patient data (HIPAA compliance)
  • High availability (24/7 operation)
  • Data integrity and accuracy
  • Integration with medical devices
  • Backup and disaster recovery

Database Solution:

  • RDBMS: PostgreSQL with advanced security features
  • Data Model: Normalized schema with proper relationships
  • Security: Role-based access control, data encryption
  • Performance: Indexing on frequently queried columns
  • Availability: High-availability cluster with failover
  • Backup: Automated daily backups with point-in-time recovery
                    -- Example: Patient Billing View
                    CREATE VIEW PatientBillingView AS
                    SELECT 
                        p.PatientID,
                        p.Name AS PatientName,
                        a.AdmissionDate,
                        r.RoomNumber,
                        r.RatePerDay,
                        DATEDIFF(day, a.AdmissionDate, COALESCE(a.DischargeDate, GETDATE())) AS DaysStayed,
                        DATEDIFF(day, a.AdmissionDate, COALESCE(a.DischargeDate, GETDATE())) * r.RatePerDay AS RoomCharges,
                        (SELECT SUM(Amount) FROM MedicalProcedures WHERE AdmissionID = a.AdmissionID) AS ProcedureCharges,
                        (SELECT SUM(Quantity * UnitPrice) FROM Prescriptions WHERE PatientID = p.PatientID) AS PharmacyCharges
                    FROM Patients p
                    JOIN Admissions a ON p.PatientID = a.PatientID
                    LEFT JOIN Rooms r ON a.RoomID = r.RoomID
                    WHERE a.DischargeDate IS NULL OR a.DischargeDate >= DATEADD(month, -1, GETDATE());
                    

🏛️ E-Governance Portal

Requirements:

  • Citizen registration and authentication
  • Document submission and tracking
  • Service request management
  • Payment processing
  • Notification system
  • Analytics and reporting

Challenges:

  • Handling high traffic volumes
  • Ensuring data security and privacy
  • Integration with multiple government systems
  • Audit trails for compliance
  • Scalability for growing user base

Database Solution:

  • Database: Distributed PostgreSQL with read replicas
  • Cache: Redis for frequently accessed data
  • Search: Elasticsearch for document search
  • Audit: Comprehensive logging of all transactions
  • Security: Multi-factor authentication, data encryption
  • Scalability: Horizontal scaling with sharding
                    -- Example: Service Request Tracking
                    CREATE TABLE ServiceRequests (
                        RequestID BIGSERIAL PRIMARY KEY,
                        CitizenID BIGINT NOT NULL,
                        ServiceType VARCHAR(100) NOT NULL,
                        RequestDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        Status VARCHAR(50) DEFAULT 'Submitted',
                        Priority VARCHAR(20) DEFAULT 'Normal',
                        AssignedTo BIGINT,
                        CompletionDate TIMESTAMP,
                        ResolutionNotes TEXT,
                        FOREIGN KEY (CitizenID) REFERENCES Citizens(CitizenID),
                        FOREIGN KEY (AssignedTo) REFERENCES GovernmentEmployees(EmployeeID)
                    );
                    
                    -- Index for performance
                    CREATE INDEX idx_service_requests_status ON ServiceRequests(Status);
                    CREATE INDEX idx_service_requests_citizen ON ServiceRequests(CitizenID);
                    CREATE INDEX idx_service_requests_date ON ServiceRequests(RequestDate);
                    

🛍️ E-Commerce Platform

Requirements:

  • Product catalog with categories and attributes
  • User accounts and profiles
  • Shopping cart functionality
  • Order processing and tracking
  • Payment gateway integration
  • Inventory management
  • Recommendation engine

Challenges:

  • Handling high traffic, especially during sales
  • Managing inventory in real-time
  • Personalized recommendations
  • Secure payment processing
  • Scalability for growing product catalog

Database Solution:

  • OLTP Database: PostgreSQL for transactional data
  • Search: Elasticsearch for product search
  • Cache: Redis for sessions and frequently accessed data
  • Analytics: Columnar database for reporting
  • Content Delivery: CDN for product images
  • Microservices: Separate services for different functions
                    -- Example: Inventory Management
                    CREATE TABLE Products (
                        ProductID BIGSERIAL PRIMARY KEY,
                        SKU VARCHAR(50) UNIQUE NOT NULL,
                        Name VARCHAR(255) NOT NULL,
                        Description TEXT,
                        Price DECIMAL(10,2) NOT NULL,
                        Cost DECIMAL(10,2),
                        CategoryID INT,
                        IsActive BOOLEAN DEFAULT true,
                        CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        UpdatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                    );
                    
                    CREATE TABLE Inventory (
                        InventoryID BIGSERIAL PRIMARY KEY,
                        ProductID BIGINT NOT NULL,
                        WarehouseID INT NOT NULL,
                        QuantityOnHand INT NOT NULL DEFAULT 0,
                        QuantityReserved INT NOT NULL DEFAULT 0,
                        ReorderPoint INT,
                        LastStockUpdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        FOREIGN KEY (ProductID) REFERENCES Products(ProductID),
                        UNIQUE (ProductID, WarehouseID)
                    );
                    
                    -- Function to check stock availability
                    CREATE OR REPLACE FUNCTION check_stock_availability(
                        p_product_id BIGINT,
                        p_warehouse_id INT,
                        p_quantity INT
                    ) RETURNS BOOLEAN AS $$
                    DECLARE
                        v_available INT;
                    BEGIN
                        SELECT (QuantityOnHand - QuantityReserved) INTO v_available
                        FROM Inventory
                        WHERE ProductID = p_product_id AND WarehouseID = p_warehouse_id;
                        
                        RETURN COALESCE(v_available, 0) >= p_quantity;
                    END;
                    $$ LANGUAGE plpgsql;
                    
Summary & Key Takeaways

Key Concepts

  • Real-world database applications are complex systems that require careful planning and design.
  • The database project lifecycle provides a structured approach to development.
  • Understanding business requirements is crucial for effective database design.
  • Scalability, performance, and security must be considered from the beginning.
  • Different types of applications require different database solutions.

Best Practices

Design Phase

  • Start with thorough requirements gathering
  • Create detailed ER diagrams
  • Normalize your data model (but denormalize when necessary for performance)
  • Plan for growth and scalability

Implementation

  • Use appropriate data types and constraints
  • Implement proper indexing strategies
  • Write efficient SQL queries
  • Implement proper security measures

Maintenance

  • Regularly monitor and optimize performance
  • Keep statistics up to date
  • Implement a robust backup and recovery strategy
  • Document all database objects and processes

Classroom Activity

Objective: Design a database for a Library Management System

Requirements:

  1. Identify the main entities and their attributes
  2. Define the relationships between entities
  3. Create an ER diagram
  4. Convert the ER diagram to a relational schema
  5. Write SQL statements to create the database
  6. Create sample queries to demonstrate functionality

Deliverables:

  • ER Diagram
  • Relational Schema
  • SQL CREATE TABLE statements
  • Sample queries with expected results

Hints:

  • Consider entities like Book, Member, Loan, Author, Publisher, etc.
  • Think about constraints (e.g., a member can't borrow more than 5 books)
  • Consider tracking book copies vs. book titles
  • Think about late returns and fines

Additional Resources

Thank You!

This concludes Lecture 22: Real-World Database Applications

Feel free to review any section using the navigation tabs above.