Way-Up

Databases

Lecture 2: Entity-Relationship Modeling & MySQL DDL

Relational databases : modeling



Key concepts in ER modeling:

Crow Foot Notation


            erDiagram
    STUDENT {
        int student_id PK
        string student_name
        string student_address
    }

    SEAT {
        int seat_no PK
        string seat_position
    }

    INSTRUCTOR {
        int instructor_no PK
        string instructor_name
        string instructor_faculty
    }

    COURSE {
        string course_name PK
        int course_number PK
    }

    SECTION {
        int section_number PK
    }

    PROFESSOR {
        int professor_id PK
        string professor_name
        string professor_faculty
    }

    %% Relationships
    STUDENT ||--o{ SEAT : "assigned"
    STUDENT }o--o{ SECTION : "enrolls"
    SECTION ||--|| COURSE : "belongs_to"
    INSTRUCTOR ||--o{ COURSE : "teaches"
    PROFESSOR ||--o{ SECTION : "teaches"
        
Credits: http://www2.cs.uregina.ca

Crow Foot Notation (2)


Connectors explanation

Exercice : a patient appointment system

Draw the following system using the crow foot notation

A doctor can be scheduled for many appointments, but may not have any scheduled at all. Each appointment is scheduled with exactly 1 doctor.

A patient can schedule 1 or more appointments. One appointment is scheduled with exactly 1 patient. An appointment must generate exactly 1 bill, a bill is generated by only 1 appointment.

One payment is applied to exactly 1 bill, and 1 bill can be paid off over time by several payments. A bill can be outstanding, having nothing yet paid on it at all. One patient can make many payments, but a single payment is made by only 1 patient.

Some patients are insured by an insurance company. If they are insured, they can only carry insurance with one company. An insurance company can have many patients carry their policies. For patients that carry insurance, the insurance company will make payments, each single payment is made by exactly 1 insurance company.

credits : http://www2.cs.uregina.ca

Toward implementation : a patient appointment system

Create the Tables corresponding to the diagram you just designed

You will probably have to add attributes to entities, like in the following examples

Remember : MySQL CREATE TABLE syntax

CREATE TABLE DOCTORS (
    doc_id INT AUTO_INCREMENT PRIMARY KEY,
    doc_firstname VARCHAR(255) NOT NULL,
    doc_lastname VARCHAR(500) NOT NULL,
    specialization VARCHAR(100),
    phone VARCHAR(20)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    

Modify table structure : ADD or DELETE columns

Syntax to modify a table : ALTER
ADD COLUMN (MySQL syntax)

ALTER TABLE DOCTORS ADD COLUMN bdate DATE;
-- Note: No quotes needed for column names in MySQL
    
DROP (REMOVE) COLUMN
ALTER TABLE DOCTORS DROP COLUMN bdate;
    

Modify table structure : duplicate columns

When you need to create a copy of a column (useful for data migration or transformations):

ADD COLUMN

ALTER TABLE DOCTORS ADD COLUMN "newCol" DATE;
UPDATE DOCTORS SET newCol = bdate;
    

Common use cases:

Best practice: Always verify data after duplication before dropping original column

Creating constraints : primary and foreign keys

In order to keep database integrity, some "keys" are necessary to implement:

Creating constraints : MySQL syntax

PRIMARY KEY

ALTER TABLE DOCTORS ADD CONSTRAINT doc_pk PRIMARY KEY (doc_id);
-- Note: MySQL doesn't use 'ONLY' keyword
    
FOREIGN KEY

ALTER TABLE APPOINTMENTS 
ADD CONSTRAINT fk_doc 
FOREIGN KEY (f_doc_id) REFERENCES DOCTORS(doc_id) 
ON DELETE SET NULL
ON UPDATE CASCADE;
    

Notice the ON DELETE SET NULL meaning that if a doctor is deleted, the appointment remains with NULL in f_doc_id

excercise : modify your scripts to integrate the constraints from the following schema

            erDiagram
            direction LR
            DOCTOR {
                string doc_physicianidnumber PK
                string doc_firstname
                string doc_lastname
            }
            APPOINTMENT {
                date app_date PK
                string app_time
                int app_duration
                string app_reason
            }
            BILL {
                int bill_number PK
                float bill_amountinsured
                float bill_amountnotinsured
                date bill_datesent
                string bill_status
            }
            PAYMENT {
                int pay_receiptnumber PK
                float pay_amount
                date pay_date
                string pay_method
            }
            PATIENT {
                int pat_idnumber PK
                string pat_firstname
                string pat_lastname
                string pat_address
                string pat_city
                string pat_state
            }
            INSURANCE_COMPANY {
                string ins_name PK
                string ins_benefitscontact
                string ins_phonenumber
                string ins_claimsaddress
            }
            DOCTOR ||--o{ APPOINTMENT : "schedules"
            PATIENT ||--o{ APPOINTMENT : "books"
            APPOINTMENT ||--|| BILL : "generates"
            BILL ||--o{ PAYMENT : "paid_by"
            PATIENT ||--o{ BILL : "receives"
            PATIENT }o--|| INSURANCE_COMPANY : "insured_by"
            INSURANCE_COMPANY ||--o{ BILL : "covers"
        
credits : http://www2.cs.uregina.ca/

Exercise: Advanced Modeling

Create a complete e-commerce database with:

Include all appropriate constraints (PRIMARY KEY, FOREIGN KEY, NOT NULL, DEFAULT, CHECK)

Exercise: Referential Integrity

For your e-commerce database, define appropriate referential integrity rules:

  1. What happens when a Customer is deleted? (CASCADE or SET NULL for Orders?)
  2. What happens when a Product is deleted while it's in active Orders?
  3. What happens when a Category parent is deleted?
  4. Should you allow Order deletion if it has Order_Items?
-- Example with different cascading rules:
ALTER TABLE Orders 
ADD CONSTRAINT fk_customer 
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id) 
ON DELETE CASCADE 
ON UPDATE CASCADE;

ALTER TABLE Order_Items 
ADD CONSTRAINT fk_product 
FOREIGN KEY (product_id) REFERENCES Products(product_id) 
ON DELETE RESTRICT 
ON UPDATE CASCADE;
    

Database Design Process

  1. Requirements Analysis: What data needs to be stored?
  2. Conceptual Design: Entity-Relationship diagram (ERD)
  3. Logical Design: Convert ERD to table schemas
  4. Normalization: Apply normal forms
  5. Physical Design: Choose data types and storage
  6. Implementation: Create actual database
  7. Testing & Optimization: Test queries and optimize performance

Good design upfront saves hours of refactoring later!

Exercise: Identify Database Concepts

For an online bookstore, identify:

  1. What are the main entities? (tables)
  2. What attributes does each entity have? (columns)
  3. What should be the primary keys?
  4. What relationships exist between entities?
  5. Which relationships are one-to-many? many-to-many?

Entities to consider: Books, Authors, Customers, Orders, Categories, Reviews

Think about real-world scenarios: Can a book have multiple authors? Can an order contain multiple books?

Exercise: Design a Social Media Database

Design the conceptual model for a simple social media platform:

Tasks:

  1. List all entities needed
  2. Identify attributes for each entity
  3. Define primary keys
  4. Map all relationships (type + cardinality)
  5. Identify which tables need junction tables

Exercise: Normalization Practice

Given this denormalized table, identify issues:

OrderID CustomerName CustomerEmail ProductNames TotalPrice
1 John Doe john@email.com Laptop, Mouse, Keyboard 1500

Questions:

  1. What's wrong with storing ProductNames as a comma-separated list?
  2. What happens if John changes his email?
  3. How would you normalize this to 3NF?
  4. Which tables would you create?

Exercise: Design a University Database

Design a database for a university system. Consider:

Tasks:

  1. Draw the ERD with all relationships
  2. Identify cardinalities (one-to-many, many-to-many)
  3. List necessary junction tables
  4. Define primary and foreign keys for each table

Common Database Design Mistakes

MySQL Storage Engines

Engine Features Use Case
InnoDB ACID compliant, Foreign Keys, Row-level locking Default, recommended for most cases
MyISAM Table-level locking, Fast reads Read-heavy, no transactions needed
MEMORY Stores data in RAM Temporary data, caching
-- Specify engine when creating table:
CREATE TABLE my_table (...) ENGINE=InnoDB;
    

Slide Overview