Popular Searches
Popular Course Categories
Popular Courses

Entity-Relationship (ER) Diagrams and Database Modeling

Entity-Relationship (ER) Diagrams and Database Modeling

Database Design and Normalization

Entity-Relationship (ER) Diagrams and Database Modeling

Course: MySQL Training

Topic: Entity-Relationship (ER) Diagrams and Database Modeling

Course Link: MySQL Training Course at JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Entity-Relationship Diagrams

An Entity-Relationship Diagram (ERD) is a visual representation of the structure of a database. It shows the entities for which data is stored, their attributes, and the relationships between them. ER diagrams help database designers understand how information is organized before creating tables and writing SQL queries.

Database modeling is the process of planning and designing the structure of a database. It involves identifying the information a system needs to store, defining entities and attributes, choosing primary keys, establishing relationships, and applying rules that maintain data accuracy and consistency.

For example, an online shopping system may need to store customers, products, orders, and payments. An ER diagram helps a developer understand how these entities are connected before implementing them in MySQL.

An ER diagram acts as a blueprint for database development. A well-designed model reduces duplicate data, makes relationships easier to understand, and provides a foundation for creating a reliable relational database.

Example of a Simple ER Model

+-------------------+       +-------------------+
|     CUSTOMERS     |       |       ORDERS      |
+-------------------+       +-------------------+
| PK customer_id    |  1  |  | PK order_id       |
|    customer_name  |-----< | FK customer_id    |
|    email          |       |    order_date     |
|    phone          |       |    total_amount   |
+-------------------+       +-------------------+

One customer can place many orders.
Each order belongs to one customer.

In this example, CUSTOMERS and ORDERS are entities. The columns inside each entity represent attributes. The line between the entities represents a one-to-many relationship.

2. Learning Objectives

After studying this topic, you should be able to:

  • Explain the meaning and purpose of an ER diagram.
  • Understand database modeling and its importance.
  • Identify entities, attributes, and relationships.
  • Understand primary keys, foreign keys, and candidate keys.
  • Recognize one-to-one, one-to-many, and many-to-many relationships.
  • Understand cardinality and participation constraints.
  • Read common ER diagram symbols and notations.
  • Convert an ER model into MySQL tables.
  • Apply normalization principles while designing a database.
  • Create a basic database model using MySQL Workbench.
  • Identify and correct common database modeling mistakes.

3. What Is Database Modeling?

Database modeling is the process of representing data requirements in a structured format before implementing a database. It helps developers determine what information must be stored, how that information should be organized, and how different records relate to each other.

For example, a college management system may need to store students, courses, instructors, departments, and enrollments. Database modeling identifies these entities and defines how they interact.

Objectives of Database Modeling

  • Organize information into meaningful entities and tables.
  • Define the attributes required for each entity.
  • Choose appropriate primary keys and foreign keys.
  • Represent business relationships correctly.
  • Reduce unnecessary duplication of data.
  • Improve data integrity and consistency.
  • Support efficient searching, reporting, and maintenance.
  • Provide a clear plan for database implementation.

Example

Suppose a college stores student details, course details, and enrollment information. Without proper modeling, the same course name might be repeated in hundreds of student records. A better design stores courses separately and uses an enrollment table to connect students and courses.

4. What Is an Entity?

An entity is a real-world object, person, place, event, or concept about which a database stores information. In a relational database, an entity type is usually implemented as a table, and each individual entity instance is represented by a row.

Examples of Entities

  • Student
  • Customer
  • Employee
  • Department
  • Product
  • Order
  • Course
  • Payment
  • Supplier

Entity Example: Student

A Student entity may contain information about students registered at a college.

student_id student_name email city
101 Rahul Sharma [email protected] Mumbai
102 Priya Patel [email protected] Pune
103 Amit Verma [email protected] Nashik

Here, Student is the entity type, while each row represents a particular student. The student_id identifies each student record.

Strong and Weak Entities

Entity Type Description Example
Strong entity Can be uniquely identified using its own key without depending on another entity for identification. Student with student_id
Weak entity Depends on an owner entity for identification and typically uses the owner's key together with a partial key. Dependent of an employee

A weak entity is not necessarily unimportant. The term describes its identification dependency in the data model.

5. What Are Attributes?

Attributes describe the properties or characteristics of an entity. When an entity is converted into a relational table, its attributes generally become columns.

For example, a Student entity may have the attributes student_id, student_name, email, and date_of_birth.

Types of Attributes

Attribute Type Meaning Example
Simple attribute Cannot meaningfully be divided into smaller attributes for the current model. Salary
Composite attribute Can be divided into meaningful components. Address divided into street, city, and postal_code
Single-valued attribute Stores one value for each entity instance. Date of birth
Multivalued attribute An entity can have multiple values for the attribute. A person with multiple phone numbers
Derived attribute Can be calculated from other stored attributes. Age calculated from date of birth
Key attribute Identifies an entity instance uniquely. student_id
Optional attribute May be unknown or not applicable for some records. Middle name

Example of Attribute Design

STUDENT
--------------------------
student_id       INT
student_name     VARCHAR(100)
email            VARCHAR(150)
date_of_birth    DATE
city             VARCHAR(80)

In this example, each attribute describes a property of a student. The selected MySQL data type determines what kind of value can be stored in each column.

6. What Is a Relationship?

A relationship describes an association between two or more entities. Relationships explain how records in one table connect to records in another table.

For example:

  • A customer places orders.
  • An employee works in a department.
  • A student enrolls in courses.
  • A supplier supplies products.
  • A user writes comments.

In a relational database, relationships are commonly implemented through primary key and foreign key constraints. A relationship in an ER model describes the business association, while the foreign key is one way to enforce that association in MySQL.

Example: Employee and Department

DEPARTMENT
-------------------------
department_id (PK)
department_name

          1
          |
          | employs
          |
          N

EMPLOYEE
-------------------------
employee_id (PK)
employee_name
department_id (FK)

One department can have multiple employees. The employee table stores the foreign key that refers to the department.

7. Types of Relationships in ER Diagrams

7.1 One-to-One Relationship

A one-to-one relationship means that each record in one entity is associated with at most one record in another entity, and vice versa. Whether participation is optional or mandatory depends on the business rules.

Example: A user and a user profile, when each user is allowed only one profile and each profile belongs to one user.

USER                    USER_PROFILE
-----------             ----------------
user_id (PK)    1 ---- 0..1 user_id (PK/FK)
username                bio
                        profile_image

A unique foreign key or shared primary key can implement a one-to-one relationship. For example, the profile's user_id can be both its primary key and a foreign key referencing the user.

7.2 One-to-Many Relationship

A one-to-many relationship allows one record in the parent entity to be associated with multiple records in the child entity. Each child record usually references one parent record.

Example: One customer can place many orders.

CUSTOMERS                ORDERS
-----------              -------------
customer_id (PK)  1 ---< order_id (PK)
customer_name             customer_id (FK)
                          order_date

The foreign key is placed in the child table, which is ORDERS in this example.

7.3 Many-to-Many Relationship

A many-to-many relationship means that multiple records in one entity can be associated with multiple records in another entity.

Example: A student can enroll in many courses, and a course can have many students.

STUDENTS             ENROLLMENTS             COURSES
----------           -------------           ----------
student_id (PK)  1 --< student_id (PK/FK)
student_name             course_id (PK/FK) >-- 1
                                              course_id (PK)
                                              course_name

In a relational database, a many-to-many relationship is normally implemented using a junction table, also called an associative or bridge table. In this example, ENROLLMENTS connects STUDENTS and COURSES.

Relationship Comparison

Relationship Meaning Implementation Example
One-to-One At most one related record on each side. Unique foreign key or shared primary key. User and profile
One-to-Many One parent can have multiple child records. Foreign key in the child table. Department and employees
Many-to-Many Multiple records on each side can be related. Junction table with foreign keys. Students and courses

8. Cardinality and Participation Constraints

Cardinality describes how many instances of one entity can be associated with instances of another entity. Participation describes whether an entity instance must participate in a relationship or may participate optionally.

Common Cardinality Expressions

Notation Meaning Example
1:1 One-to-one One user to one profile, subject to the model's participation rules
1:N One-to-many One department to many employees
M:N Many-to-many Many students to many courses
0..1 Zero or one related instance An employee may have zero or one assigned parking space
1..N One or more related instances A business rule may require each order to contain at least one item
0..N Zero or more related instances A customer may have no orders or many orders

Optional Participation

Optional participation means an entity can exist without participating in a particular relationship. For example, a newly registered customer may not have placed any orders.

Mandatory Participation

Mandatory participation means an entity must participate in a relationship under the defined business rules. For example, an order may be required to belong to a customer.

In MySQL, a foreign key declared NOT NULL can require every child row to reference a parent. However, a foreign key alone does not guarantee that every parent has at least one child.

9. ER Diagram Symbols and Notations

Different ER modeling tools support different notations. Two commonly encountered approaches are Chen notation and Crow's Foot notation.

Symbol or Element Meaning Typical Use
Rectangle Entity Represents Student or Customer
Oval Attribute in Chen notation Represents student_name or email
Diamond Relationship in Chen notation Represents a student enrolling in a course
Underlined attribute Key attribute in traditional ER notation Shows a unique identifier
Single line Relationship connection Connects entities and relationships
Crow's foot Many end of a relationship in Crow's Foot notation Shows multiple child records
Circle Often represents optional participation in Crow's Foot notation Zero related records are allowed
Bar Often represents one in Crow's Foot notation Exactly one at that endpoint

Always check the notation used by your modeling tool. The same relationship can look different in Chen, Crow's Foot, or other diagram styles.

10. Keys in Database Modeling

Keys identify records and connect tables. Selecting suitable keys is an important part of designing a reliable relational database.

10.1 Primary Key

A primary key uniquely identifies each row in a table. A primary key cannot contain NULL values, and a table can have only one primary key definition, which may consist of multiple columns.

CREATE TABLE students (
    student_id INT AUTO_INCREMENT PRIMARY KEY,
    student_name VARCHAR(100) NOT NULL
);

10.2 Foreign Key

A foreign key references a key in another table, or in the same table for a self-referencing relationship. It helps MySQL enforce referential integrity.

CREATE TABLE enrollments (
    enrollment_id INT AUTO_INCREMENT PRIMARY KEY,
    student_id INT NOT NULL,
    CONSTRAINT fk_enrollments_student
        FOREIGN KEY (student_id)
        REFERENCES students(student_id)
);

10.3 Candidate Key

A candidate key is a minimal set of attributes that can uniquely identify each record. A table can have multiple candidate keys, but one is selected as the primary key.

For example, if both student_id and email are guaranteed to be unique and non-NULL, either could potentially serve as a candidate key.

10.4 Composite Key

A composite key consists of two or more columns used together to identify a record uniquely.

CREATE TABLE enrollments (
    student_id INT NOT NULL,
    course_id INT NOT NULL,
    enrollment_date DATE NOT NULL,
    PRIMARY KEY (student_id, course_id)
);

This composite primary key prevents the same student-course pair from appearing more than once. If the system must preserve multiple enrollment attempts for the same course, the key design would need to include an attempt identifier or another suitable unique key.

10.5 Unique Key

A UNIQUE constraint prevents duplicate combinations of values. Unlike a primary key, a MySQL UNIQUE index can permit NULL values, subject to MySQL's handling of NULLs and the specific column definition.

CREATE TABLE users (
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(150) NOT NULL UNIQUE
);

11. Conceptual, Logical, and Physical Database Models

Database modeling is commonly divided into three levels. Each level describes the database at a different degree of detail.

Model Level Purpose Includes Example
Conceptual model Describes business data requirements at a high level. Main entities and their relationships. Customers place orders.
Logical model Defines the detailed data structure independently of specific storage implementation. Attributes, keys, relationships, and normalization. Customer has customer_id and name; Order references Customer.
Physical model Defines how the model will be implemented in a particular database system. MySQL data types, indexes, constraints, storage details, and table definitions. CREATE TABLE statements using InnoDB.

Example of Moving Between the Levels

  • Conceptual: A customer places orders.
  • Logical: CUSTOMER and ORDER entities are connected by a one-to-many relationship, with customer_id as the parent key.
  • Physical: Create customers and orders tables with integer keys and a MySQL foreign key constraint.

12. Database Normalization and ER Modeling

Normalization is the process of organizing relational data to reduce unnecessary duplication and avoid common insertion, update, and deletion anomalies. It is closely related to ER modeling because the model helps identify entities that should be stored separately.

First Normal Form (1NF)

A table is in First Normal Form when each column contains a single value from its intended domain rather than a repeating list of values in one cell, and the table structure does not use repeating groups of columns.

Incorrect design:

STUDENT
-----------------------------------
student_id | student_name | phones
1          | Rahul        | 9876, 1234

Improved design:

STUDENTS
-------------------------------
student_id (PK) | student_name

STUDENT_PHONES
-------------------------------
student_id (FK) | phone_number

Each phone number is stored in its own row in STUDENT_PHONES. This design supports multiple phone numbers without placing a comma-separated list inside a column.

Second Normal Form (2NF)

A table is in Second Normal Form when it is in 1NF and every non-key attribute depends on the whole candidate key, not just part of a composite candidate key.

For example, if a table uses (student_id, course_id) as a composite key, a student's name depends only on student_id, not on the full pair. Student details should therefore be stored in a separate STUDENTS table.

Third Normal Form (3NF)

A table is in Third Normal Form when it is in 2NF and non-key attributes do not depend transitively on a candidate key through another non-key attribute, subject to the formal 3NF definition.

For example, if each department ID determines a department name, storing department_name repeatedly in every employee row creates unnecessary duplication. A separate DEPARTMENTS table can store the department name once, and EMPLOYEES can reference it using department_id.

13. Step-by-Step Process for Creating an ER Diagram

Step 1: Understand the Business Requirements

Gather information about the system and identify what data must be stored. Ask questions such as:

  • What information must the application manage?
  • Who will use the system?
  • What reports or queries are required?
  • What business rules govern the information?
  • Which records must be connected?

Step 2: Identify Entities

List the main objects the system needs to track. For an online store, entities may include CUSTOMERS, PRODUCTS, ORDERS, ORDER_ITEMS, and PAYMENTS.

Step 3: Identify Attributes

Determine the properties that describe each entity. For example, CUSTOMERS may include customer_id, customer_name, email, and phone.

Step 4: Choose Primary Keys

Select a stable identifier for every entity. Primary keys should uniquely identify rows and should not depend on changeable business details unless there is a strong reason to do so.

Step 5: Identify Relationships

Determine how entities interact. Ask whether the relationship is one-to-one, one-to-many, or many-to-many, and whether participation is optional or mandatory.

Step 6: Define Foreign Keys

Place foreign keys on the appropriate side of the relationship. For a one-to-many relationship, the foreign key normally belongs in the child table. For a many-to-many relationship, create a junction table.

Step 7: Apply Normalization

Review the model for repeated groups, duplicated facts, and dependencies that indicate data should be stored in separate entities.

Step 8: Choose Data Types and Constraints

For the physical MySQL design, choose appropriate data types and constraints such as NOT NULL, UNIQUE, CHECK where appropriate, PRIMARY KEY, and FOREIGN KEY.

Step 9: Review the Diagram

Confirm that all important entities, attributes, keys, and relationships are present. Check whether the diagram accurately represents the actual business rules.

Step 10: Implement and Test

Create the tables in MySQL, insert sample data, and test the relationships. Verify that valid operations succeed and invalid operations are rejected where expected.

14. Practical Example: College Management System ER Model

Consider a college that manages students, courses, instructors, and student enrollments. A student may enroll in multiple courses, and each course may contain many students. This requires a many-to-many relationship between STUDENTS and COURSES, implemented through ENROLLMENTS.

Entities

  • STUDENTS: Stores student information.
  • COURSES: Stores course information.
  • ENROLLMENTS: Connects students to courses and records enrollment details.
  • INSTRUCTORS: Stores instructor information.

ER Model Structure

+-------------------+       +----------------------+
|     STUDENTS      |       |      ENROLLMENTS     |
+-------------------+       +----------------------+
| PK student_id     |  1  |  | PK, FK student_id    |
|    student_name   |-----< | PK, FK course_id     |
|    email          |       |    enrollment_date   |
+-------------------+       +----------------------+
                                      >----- 1
                              +-------------------+
                              |      COURSES      |
                              +-------------------+
                              | PK course_id      |
                              |    course_name    |
                              | FK instructor_id  |
                              +-------------------+
                                      >----- 1
                              +-------------------+
                              |    INSTRUCTORS    |
                              +-------------------+
                              | PK instructor_id  |
                              |    instructor_name|
                              +-------------------+

In this simplified model, one instructor may teach multiple courses, while each course references one instructor. ENROLLMENTS resolves the many-to-many relationship between students and courses.

15. Implementing the ER Model in MySQL

Step 1: Create the Database

CREATE DATABASE college_db;
USE college_db;

Step 2: Create the Students Table

CREATE TABLE students (
    student_id INT AUTO_INCREMENT PRIMARY KEY,
    student_name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE
) ENGINE = InnoDB;

Step 3: Create the Instructors Table

CREATE TABLE instructors (
    instructor_id INT AUTO_INCREMENT PRIMARY KEY,
    instructor_name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE
) ENGINE = InnoDB;

Step 4: Create the Courses Table

CREATE TABLE courses (
    course_id INT AUTO_INCREMENT PRIMARY KEY,
    course_name VARCHAR(100) NOT NULL,
    instructor_id INT NOT NULL,
    CONSTRAINT fk_courses_instructor
        FOREIGN KEY (instructor_id)
        REFERENCES instructors(instructor_id)
) ENGINE = InnoDB;

Step 5: Create the Enrollments Table

CREATE TABLE enrollments (
    student_id INT NOT NULL,
    course_id INT NOT NULL,
    enrollment_date DATE NOT NULL,
    PRIMARY KEY (student_id, course_id),
    CONSTRAINT fk_enrollments_student
        FOREIGN KEY (student_id)
        REFERENCES students(student_id),
    CONSTRAINT fk_enrollments_course
        FOREIGN KEY (course_id)
        REFERENCES courses(course_id)
) ENGINE = InnoDB;

The ENROLLMENTS table has a composite primary key. This design allows a student to enroll in multiple courses and each course to have multiple students, while preventing duplicate student-course pairs.

Step 6: Insert Sample Data

INSERT INTO students (student_name, email)
VALUES
('Rahul Sharma', '[email protected]'),
('Priya Patel', '[email protected]'),
('Amit Verma', '[email protected]');

INSERT INTO instructors (instructor_name, email)
VALUES
('Neha Joshi', '[email protected]'),
('Karan Mehta', '[email protected]');

INSERT INTO courses (course_name, instructor_id)
VALUES
('MySQL Fundamentals', 1),
('Database Design', 1),
('SQL Reporting', 2);

INSERT INTO enrollments (student_id, course_id, enrollment_date)
VALUES
(1, 1, '2026-10-01'),
(1, 2, '2026-10-02'),
(2, 1, '2026-10-03'),
(3, 3, '2026-10-04');

These statements assume the newly created tables have no previous records and that the generated IDs correspond to the inserted rows.

Step 7: Display Students and Their Courses

SELECT
    s.student_id,
    s.student_name,
    c.course_name,
    e.enrollment_date
FROM students AS s
INNER JOIN enrollments AS e
    ON s.student_id = e.student_id
INNER JOIN courses AS c
    ON e.course_id = c.course_id
ORDER BY s.student_id, c.course_name;

This query follows the relationships in the model to display the courses associated with each student.

Step 8: Find Students Who Are Not Enrolled

SELECT
    s.student_id,
    s.student_name
FROM students AS s
LEFT JOIN enrollments AS e
    ON s.student_id = e.student_id
WHERE e.student_id IS NULL;

This query returns students who do not currently have an enrollment record.

16. Using MySQL Workbench for Database Modeling

MySQL Workbench is a visual tool that supports database modeling and EER diagrams. It allows developers to create tables, add columns and keys, define relationships, and generate SQL from a model.

Steps to Create an EER Diagram

  1. Open MySQL Workbench.
  2. Create a new model using the model creation option.
  3. Add an EER diagram to the model.
  4. Add tables for the entities required by the application.
  5. Define each table's columns and data types.
  6. Mark the primary key columns.
  7. Create relationships using the relationship tools.
  8. Verify that foreign keys and relationship cardinality are correct.
  9. Arrange the tables so the diagram is easy to read.
  10. Use the forward-engineering feature to generate a database schema when ready.
  11. Review the generated SQL and test it against the intended MySQL environment.

MySQL Workbench provides relationship tools for one-to-one, one-to-many, and many-to-many designs. In a typical one-to-many relationship, the foreign key is placed in the table on the many side.

Reference: MySQL Workbench: Adding Foreign Key Relationships Using an EER Diagram

17. Converting an ER Diagram into Relational Tables

After designing an ER diagram, the next step is mapping its entities and relationships to relational tables.

ER Model Element Relational Database Representation
Strong entity Usually becomes a table with its attributes as columns.
Attribute Usually becomes a column.
Key attribute Becomes a primary key or part of a key.
One-to-one relationship Often implemented using a unique foreign key or shared primary key.
One-to-many relationship Usually implemented with a foreign key in the child table.
Many-to-many relationship Usually becomes a junction table with foreign keys to both entities.
Multivalued attribute Often becomes a separate table linked to the original entity.
Weak entity Usually becomes a table containing the owner's key and its own identifying attributes.

The mapping depends on the precise business rules. For example, an optional one-to-one relationship may need a nullable unique foreign key, while a mandatory one-to-one relationship may need additional constraints or a different table design.

18. ER Diagrams and Data Integrity

A well-designed ER model helps establish rules that keep stored data accurate and consistent. These rules are implemented using relational constraints and appropriate application logic.

Entity Integrity

Entity integrity means that each table row can be uniquely identified. In MySQL, primary keys enforce uniqueness and disallow NULL values in the key columns.

Referential Integrity

Referential integrity means that foreign key values must reference valid parent keys unless the foreign key value is NULL and the relationship allows it.

Domain Integrity

Domain integrity ensures that column values conform to their intended types and permitted ranges. It can be supported through data types, NOT NULL, UNIQUE, CHECK constraints where supported, and other rules.

Business Rules

Business rules describe requirements specific to the application. For example, an order total cannot be negative, and an enrollment may only be allowed for an active course. Some business rules can be implemented with constraints, while others may require transactions, triggers, or application-level validation.

19. Common ER Modeling Mistakes

Mistake Problem Solution
Missing primary keys Rows may be difficult to identify uniquely. Define an appropriate primary key for every table.
Incorrect relationship cardinality The model does not represent the real business rules. Confirm how many records may be associated on each side.
Missing foreign keys Invalid references may be stored without database enforcement. Define foreign key constraints where appropriate.
Storing multiple values in one column Searching and updating individual values becomes difficult. Use a separate table for multivalued attributes.
Incorrect many-to-many design Repeated columns or duplicate data may result. Use a junction table.
Duplicating the same facts across tables Updates can become inconsistent. Review functional dependencies and normalization.
Using inappropriate data types Values may be stored inaccurately or take unnecessary space. Select data types based on the values and required operations.
Overcomplicating the model The design becomes difficult to understand and maintain. Keep entities focused and relationships meaningful.
Ignoring optional participation The database may reject valid records or allow invalid ones. Decide whether relationships are mandatory or optional.
Using destructive cascading actions carelessly Deleting one parent may remove many child records. Choose ON DELETE actions based on data-retention requirements.

20. Testing and Validating a Database Model

Before using a database model in a real application, test the schema against representative use cases.

Validation Checklist

  • Every required entity is represented.
  • Each table has a suitable primary key.
  • Attributes have appropriate data types.
  • Relationships represent the actual business rules.
  • Foreign keys reference the intended parent keys.
  • Mandatory relationships are correctly enforced.
  • Optional relationships allow NULL only when appropriate.
  • Many-to-many relationships use suitable junction tables.
  • Unique constraints prevent duplicate values where necessary.
  • Normalization has been reviewed for avoidable duplication.
  • Required indexes exist for important queries and constraints.
  • Insert, update, and delete operations behave as expected.
  • Reports and joins return the expected results.

Example Validation Queries

-- Display the table definition
SHOW CREATE TABLE enrollments;

-- Check student records
SELECT * FROM students;

-- Check course records
SELECT * FROM courses;

-- Check enrollment relationships
SELECT
    student_id,
    course_id,
    enrollment_date
FROM enrollments;

-- Inspect a query execution plan
EXPLAIN
SELECT s.student_name, c.course_name
FROM students AS s
JOIN enrollments AS e
    ON s.student_id = e.student_id
JOIN courses AS c
    ON e.course_id = c.course_id;

Validation should include both valid and invalid test cases. For example, attempt to insert an enrollment for a nonexistent student and confirm that the foreign key constraint rejects it.

21. Practical Project: Online Shopping Database Model

Project objective: Design a basic database for an online shopping platform that manages customers, products, orders, and order items.

Requirements

  • A customer can place multiple orders.
  • An order belongs to one customer.
  • An order can contain multiple products.
  • A product can appear in multiple orders.
  • Each order item records the quantity and price for a product at the time of ordering.

Entity Relationship Structure

CUSTOMERS
customer_id (PK)
customer_name
email
     |
     | 1 to many
     v
ORDERS
order_id (PK)
customer_id (FK)
order_date
     |
     | 1 to many
     v
ORDER_ITEMS
order_id (PK, FK)
product_id (PK, FK)
quantity
unit_price
     ^
     | many to 1
     |
PRODUCTS
product_id (PK)
product_name
current_price

The ORDER_ITEMS table resolves the many-to-many relationship between ORDERS and PRODUCTS. The unit_price stored in an order item represents the price charged for that item at the time of purchase; it should not automatically change when the product's current price changes.

Implementation

CREATE DATABASE shopping_model;
USE shopping_model;

CREATE TABLE customers (
    customer_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE
) ENGINE = InnoDB;

CREATE TABLE products (
    product_id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(150) NOT NULL,
    current_price DECIMAL(10, 2) NOT NULL
) ENGINE = InnoDB;

CREATE TABLE orders (
    order_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT NOT NULL,
    order_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_orders_customers
        FOREIGN KEY (customer_id)
        REFERENCES customers(customer_id)
) ENGINE = InnoDB;

CREATE TABLE order_items (
    order_id INT NOT NULL,
    product_id INT NOT NULL,
    quantity INT NOT NULL,
    unit_price DECIMAL(10, 2) NOT NULL,
    PRIMARY KEY (order_id, product_id),
    CONSTRAINT fk_items_orders
        FOREIGN KEY (order_id)
        REFERENCES orders(order_id),
    CONSTRAINT fk_items_products
        FOREIGN KEY (product_id)
        REFERENCES products(product_id)
) ENGINE = InnoDB;

This example uses a composite primary key in ORDER_ITEMS, so the same product can appear only once per order. If the business needs to allow multiple separate lines for the same product in one order, introduce an order_item_id or another suitable line identifier instead.

Project Queries

Query 1: Display orders with customer names.

SELECT
    o.order_id,
    c.customer_name,
    o.order_date
FROM orders AS o
INNER JOIN customers AS c
    ON o.customer_id = c.customer_id;

Query 2: Display items for each order.

SELECT
    oi.order_id,
    p.product_name,
    oi.quantity,
    oi.unit_price,
    oi.quantity * oi.unit_price AS line_total
FROM order_items AS oi
INNER JOIN products AS p
    ON oi.product_id = p.product_id
ORDER BY oi.order_id, p.product_name;

Query 3: Calculate the total for each order.

SELECT
    order_id,
    SUM(quantity * unit_price) AS order_total
FROM order_items
GROUP BY order_id;

Project Extensions

  • Add product categories and model the relationship between categories and products.
  • Add payment records and define the appropriate relationship with orders.
  • Add shipping addresses and decide whether each order needs an address snapshot.
  • Introduce status columns for orders and payments.
  • Test primary keys, foreign keys, and unique constraints.
  • Create an ER diagram in MySQL Workbench and compare it with the SQL schema.

22. Interview Questions and Answers

Q1. What is an ER diagram?

An ER diagram is a visual representation of entities, their attributes, and the relationships between them. It is used to plan and communicate database structure.

Q2. What is database modeling?

Database modeling is the process of designing how information will be structured, stored, related, and constrained in a database.

Q3. What is an entity?

An entity is a real-world object or concept about which the database stores information, such as a student, customer, product, or order.

Q4. What is an attribute?

An attribute describes a property of an entity. For example, student_name and date_of_birth can be attributes of STUDENT.

Q5. What is a relationship in an ER diagram?

A relationship represents an association between entities, such as a customer placing orders or a student enrolling in courses.

Q6. What is cardinality?

Cardinality describes how many instances of one entity can be associated with instances of another entity. Common types are one-to-one, one-to-many, and many-to-many.

Q7. What is the difference between a primary key and a foreign key?

A primary key uniquely identifies a row in its own table. A foreign key references a key in another table, or sometimes the same table, to represent and enforce a relationship.

Q8. How is a many-to-many relationship implemented in MySQL?

A many-to-many relationship is usually implemented with a junction table containing foreign keys to both related tables. The keys may form a composite primary key or be combined with a separate unique constraint.

Q9. What is a weak entity?

A weak entity depends on an owner entity for identification. It often uses the owner's key together with a partial key to identify its records.

Q10. What is normalization?

Normalization organizes relational data to reduce unnecessary duplication and prevent common insertion, update, and deletion anomalies.

Q11. What is the difference between conceptual and physical database modeling?

Conceptual modeling describes business entities and relationships at a high level. Physical modeling defines the database-specific implementation, including MySQL data types, indexes, and constraints.

Q12. What is MySQL Workbench used for in database modeling?

MySQL Workbench can be used to create EER diagrams, define tables and relationships, and generate SQL for implementing a database schema.

Q13. Why is a junction table needed?

A junction table converts a many-to-many relationship into two one-to-many relationships, making the relationship practical to implement in a relational database.

Q14. What is referential integrity?

Referential integrity ensures that foreign key references remain valid according to the constraints defined in the database.

Q15. Why should database modeling be completed before implementation?

Modeling helps reveal missing entities, incorrect relationships, duplicate data, and unclear business rules before they become costly changes in the implemented database.

23. Quick Revision Notes

  • ER stands for Entity-Relationship.
  • An ER diagram visually represents entities, attributes, and relationships.
  • Database modeling plans how information is organized before implementation.
  • Entities generally become tables in a relational database.
  • Attributes generally become columns.
  • Primary keys uniquely identify rows.
  • Foreign keys connect related tables and can enforce referential integrity.
  • One-to-one relationships associate at most one record on each side.
  • One-to-many relationships place the foreign key on the child side.
  • Many-to-many relationships normally use a junction table.
  • Cardinality describes the number of possible related records.
  • Participation can be optional or mandatory.
  • Normalization reduces unnecessary duplication and data anomalies.
  • Conceptual, logical, and physical models represent different levels of detail.
  • MySQL Workbench can help create EER diagrams and generate SQL.
  • Always validate a model against real business requirements and test the resulting schema.

24. Conclusion

Entity-Relationship diagrams and database modeling are fundamental skills for designing reliable MySQL databases. ER diagrams help visualize entities, attributes, keys, and relationships before tables are created. A clear model makes it easier to identify one-to-one, one-to-many, and many-to-many relationships and implement them using appropriate primary keys, foreign keys, and junction tables.

By combining ER modeling with normalization, suitable data types, integrity constraints, and practical testing, developers can create database structures that are easier to understand, maintain, and extend. Practice the college management and online shopping examples to develop confidence in turning business requirements into working MySQL schemas.

25. Additional Learning Resources

whatsapp