Table of Contents

    Entities and relationships

    RELATIONAL DATA MODELING & SQL

    Entities and Relationships

    Learn how to identify entities, define attributes and keys, model one-to-one, one-to-many, and many-to-many relationships, establish cardinality and participation constraints, and translate a conceptual data model into relational database tables.

    Introduction

    Database design begins with understanding the information an application needs to store. Before creating tables or writing SQL, the designer should identify the important business objects, their properties, and the relationships connecting them.

    The Entity-Relationship model, commonly called the ER model, provides a conceptual method for representing this information.

    The ER model describes:

    • Entities about which information is stored
    • Attributes that describe those entities
    • Keys that uniquely identify entity instances
    • Relationships connecting entities
    • Cardinality rules for those relationships
    • Participation and optionality constraints
    • Business rules that the data model must preserve

    Core idea: An entity represents something important to the domain, an attribute describes it, and a relationship explains how it is associated with another entity.

    In your System Design curriculum, Entities and Relationships is Topic 5.1 and begins the Relational Data Modeling & SQL module. It is followed by normalization and denormalization, keys and constraints, ACID, transactions, isolation, indexes, query plans, and connection pools.

    Prerequisites

    # Prerequisite Why It Is Needed
    1 Basic database concepts Entities are commonly implemented as relational database tables.
    2 Basic SQL The examples use SQL to translate conceptual entities into tables.
    3 Data types Attributes require suitable string, numeric, date, Boolean, and identifier types.
    4 Resource modeling Domain concepts can influence both API resources and database entities.
    5 Business requirements Relationships and constraints must reflect actual business rules.

    What Is an Entity?

    An entity is a distinguishable object, event, place, person, concept, or transaction about which the system needs to store information.

    Examples include:

    • Customer
    • Product
    • Order
    • Invoice
    • Payment
    • Employee
    • Department
    • Course
    • Reservation
    • Shipment

    Entity Type vs Entity Instance

    Concept Meaning Example
    Entity type The general category or structure Customer
    Entity instance One identifiable occurrence of the entity type Customer CUS-42
    Entity set The collection of all entity instances of one type All customers
    Entity type:
    
    Customer
    
    
    Entity instances:
    
    Customer CUS-42
    Customer CUS-43
    Customer CUS-44
    
    
    Entity set:
    
    All customer instances

    What Is an Attribute?

    An attribute is a property or characteristic that describes an entity or relationship.

    Customer Attributes

    Customer
    
    - Customer ID
    - Display name
    - Email address
    - Phone number
    - Status
    - Created time

    Product Attributes

    Product
    
    - Product ID
    - Product name
    - Description
    - Unit price
    - Status
    - Category

    Every attribute should have a clear definition, data type, allowed format, nullability rule, and business meaning.

    Types of Attributes

    Attribute Type Meaning Example
    Simple attribute Cannot meaningfully be divided within the model Customer status
    Composite attribute Contains several meaningful components Address containing city, postal code, and country
    Single-valued attribute Has one value for each entity instance Date of birth
    Multi-valued attribute Can have several values for one entity Several telephone numbers
    Derived attribute Calculated from other stored information Order total
    Optional attribute Can be absent for a valid entity Middle name
    Identifier attribute Participates in uniquely identifying an entity Customer ID

    Composite Attributes

    A composite attribute contains several components that have independent meaning.

    Address
    
    - Address line 1
    - Address line 2
    - City
    - State or region
    - Postal code
    - Country code

    Storing these components separately supports validation, filtering, sorting, searching, and country-specific formatting.

    Unstructured address
    shipping_address VARCHAR(1000)
    Structured address attributes
    address_line_1 VARCHAR(200),
    address_line_2 VARCHAR(200),
    city VARCHAR(100),
    region VARCHAR(100),
    postal_code VARCHAR(30),
    country_code CHAR(2)

    Multi-valued Attributes

    A multi-valued attribute can contain several values for one entity.

    Customer CUS-42
    
    Telephone numbers:
    
    - +91-0000000001
    - +91-0000000002
    - +91-0000000003

    In a relational database, repeated values should normally be modeled using a related table instead of placing several values in one column.

    Several values in one column
    phone_numbers VARCHAR(1000)
    Stored value:
    
    +91-0000000001,+91-0000000002,+91-0000000003
    Related telephone entity
    CREATE TABLE customer_phone_numbers
    (
        phone_number_id BIGINT PRIMARY KEY,
        customer_id BIGINT NOT NULL,
        phone_number VARCHAR(30) NOT NULL,
        phone_type VARCHAR(20) NOT NULL,
        is_primary BOOLEAN NOT NULL DEFAULT FALSE
    );

    Derived Attributes

    A derived attribute is calculated from other data.

    Order total
    =
    Sum of line amounts
    +
    Tax
    +
    Shipping
    -
    Discounts

    A derived value can be calculated when queried or stored when performance, legal, historical, or audit requirements justify materializing it.

    Consistency rule: When a derived value is stored, define how it remains synchronized with the source attributes.

    Keys and Entity Identity

    A key identifies an entity instance and supports references between related entities.

    Key Type Meaning
    Super key One or more attributes capable of uniquely identifying an entity
    Candidate key A minimal super key with no unnecessary attribute
    Primary key The candidate key selected as the main relational identifier
    Alternate key A candidate key not selected as the primary key
    Composite key A key containing more than one attribute
    Foreign key An attribute or attribute set referencing a key in another table
    Surrogate key A system-generated identifier without domain meaning
    Natural key An identifier derived from meaningful domain data

    Primary and Alternate Keys

    CREATE TABLE customers
    (
        customer_id BIGINT PRIMARY KEY,
        customer_number VARCHAR(30) NOT NULL,
        email_address VARCHAR(254) NOT NULL,
        display_name VARCHAR(200) NOT NULL,
    
        CONSTRAINT uq_customers_customer_number
            UNIQUE (customer_number),
    
        CONSTRAINT uq_customers_email
            UNIQUE (email_address)
    );

    The system-generated customer_id is the primary key, while the customer number and email address can be alternate candidate keys when the business rules guarantee uniqueness.

    What Is a Relationship?

    A relationship represents an association between entity instances.

    Customer places Order.
    
    Order contains Order Line.
    
    Order Line references Product.
    
    Order has Payment.
    
    Order produces Shipment.

    A relationship type defines the general association, while a relationship instance represents one actual association.

    Concept Example
    Relationship type Customer places Order
    Relationship instance Customer CUS-42 placed Order ORD-9001

    Degree of a Relationship

    The degree describes the number of participating entity types.

    Degree Name Example
    1 Unary or recursive Employee manages Employee
    2 Binary Customer places Order
    3 Ternary Supplier supplies Product to Warehouse
    More than 3 N-ary A relationship involving several participating entity types

    Cardinality

    Cardinality defines how many instances of one entity can be associated with instances of another entity.

    The principal cardinality patterns are:

    • One-to-one
    • One-to-many
    • Many-to-one
    • Many-to-many

    One-to-one Relationship

    In a one-to-one relationship, one instance of entity A can be related to at most one instance of entity B, and one instance of entity B can be related to at most one instance of entity A.

    User Account 1 -------- 1 User Profile

    SQL Implementation

    CREATE TABLE user_accounts
    (
        user_id BIGINT PRIMARY KEY,
        username VARCHAR(100) NOT NULL UNIQUE
    );
    
    CREATE TABLE user_profiles
    (
        user_id BIGINT PRIMARY KEY,
        display_name VARCHAR(200) NOT NULL,
        biography VARCHAR(1000) NULL,
    
        CONSTRAINT fk_user_profiles_user
            FOREIGN KEY (user_id)
            REFERENCES user_accounts (user_id)
    );

    Using the parent key as both the primary key and foreign key in user_profiles ensures that each account can have at most one profile.

    One-to-many Relationship

    In a one-to-many relationship, one parent entity can be associated with several child entities, while each child belongs to one parent.

    Customer 1 -------- N Orders

    SQL Implementation

    CREATE TABLE customers
    (
        customer_id BIGINT PRIMARY KEY,
        customer_number VARCHAR(30) NOT NULL UNIQUE,
        display_name VARCHAR(200) NOT NULL
    );
    
    CREATE TABLE orders
    (
        order_id BIGINT PRIMARY KEY,
        order_number VARCHAR(30) NOT NULL UNIQUE,
        customer_id BIGINT NOT NULL,
        order_status VARCHAR(30) NOT NULL,
        created_at TIMESTAMP NOT NULL,
    
        CONSTRAINT fk_orders_customer
            FOREIGN KEY (customer_id)
            REFERENCES customers (customer_id)
    );

    The foreign key appears on the many side. Several order rows can reference the same customer row.

    Many-to-many Relationship

    In a many-to-many relationship, several instances of entity A can relate to several instances of entity B.

    Students N -------- N Courses

    A relational database normally resolves this relationship through an associative or junction table.

    Junction-table Implementation

    CREATE TABLE students
    (
        student_id BIGINT PRIMARY KEY,
        student_number VARCHAR(30) NOT NULL UNIQUE,
        student_name VARCHAR(200) NOT NULL
    );
    
    CREATE TABLE courses
    (
        course_id BIGINT PRIMARY KEY,
        course_code VARCHAR(30) NOT NULL UNIQUE,
        course_title VARCHAR(200) NOT NULL
    );
    
    CREATE TABLE enrollments
    (
        student_id BIGINT NOT NULL,
        course_id BIGINT NOT NULL,
        enrolled_at TIMESTAMP NOT NULL,
        enrollment_status VARCHAR(30) NOT NULL,
        final_grade VARCHAR(10) 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)
    );

    The enrollments table does more than connect students and courses. It also stores attributes belonging to the relationship, such as enrollment time, status, and final grade.

    Modeling rule: When a many-to-many relationship has its own attributes, lifecycle, or business rules, treat the junction as a meaningful associative entity.

    Associative Entities

    An associative entity represents a relationship that has become important enough to be modeled as an entity in its own right.

    Project Membership Example

    User N -------- N Project
    
    Resolved through:
    
    Project Membership
    
    
    Project Membership attributes:
    
    - Membership ID
    - User ID
    - Project ID
    - Role
    - Joined time
    - Status
    CREATE TABLE project_memberships
    (
        membership_id BIGINT PRIMARY KEY,
        project_id BIGINT NOT NULL,
        user_id BIGINT NOT NULL,
        membership_role VARCHAR(50) NOT NULL,
        membership_status VARCHAR(30) NOT NULL,
        joined_at TIMESTAMP NOT NULL,
    
        CONSTRAINT uq_project_memberships
            UNIQUE
            (
                project_id,
                user_id
            ),
    
        CONSTRAINT fk_memberships_project
            FOREIGN KEY (project_id)
            REFERENCES projects (project_id),
    
        CONSTRAINT fk_memberships_user
            FOREIGN KEY (user_id)
            REFERENCES users (user_id)
    );

    Recursive Relationships

    A recursive relationship connects instances of one entity type to other instances of the same type.

    Employee Reporting Structure

    Employee
       |
       | reports to
       v
    Employee
    CREATE TABLE employees
    (
        employee_id BIGINT PRIMARY KEY,
        employee_number VARCHAR(30) NOT NULL UNIQUE,
        employee_name VARCHAR(200) NOT NULL,
        manager_employee_id BIGINT NULL,
    
        CONSTRAINT fk_employees_manager
            FOREIGN KEY (manager_employee_id)
            REFERENCES employees (employee_id)
    );

    A top-level employee can have a null manager reference, while other employees can reference another employee as manager.

    Ternary Relationships

    A ternary relationship connects three entity types in one association.

    Supplier supplies Product to Warehouse

    The meaning can depend on all three participants. Replacing it with several independent binary relationships can lose information.

    CREATE TABLE supplier_product_warehouse
    (
        supplier_id BIGINT NOT NULL,
        product_id BIGINT NOT NULL,
        warehouse_id BIGINT NOT NULL,
        supplier_price DECIMAL(18, 2) NOT NULL,
        lead_time_days INT NOT NULL,
    
        PRIMARY KEY
        (
            supplier_id,
            product_id,
            warehouse_id
        ),
    
        FOREIGN KEY (supplier_id)
            REFERENCES suppliers (supplier_id),
    
        FOREIGN KEY (product_id)
            REFERENCES products (product_id),
    
        FOREIGN KEY (warehouse_id)
            REFERENCES warehouses (warehouse_id)
    );

    Participation Constraints

    Participation describes whether an entity is required to participate in a relationship.

    Participation Meaning Example
    Total or mandatory Every entity instance must participate in the relationship Every order must belong to a customer
    Partial or optional An entity instance can exist without participating An employee can exist without an assigned manager

    Mandatory Participation

    customer_id BIGINT NOT NULL

    Optional Participation

    manager_employee_id BIGINT NULL

    Optionality rule: Use nullability only when absence has a valid and documented business meaning.

    Minimum and Maximum Cardinality

    Relationship constraints can be expressed using minimum and maximum participation.

    Notation Meaning
    0..1 Zero or one related instance
    1..1 Exactly one related instance
    0..* Zero or many related instances
    1..* One or many related instances

    Order Example

    Customer to Orders:
    
    Customer:
    0..* Orders
    
    Order:
    1..1 Customer
    
    
    Order to Order Lines:
    
    Order:
    1..* Order Lines
    
    Order Line:
    1..1 Order

    Some minimum-cardinality rules, such as requiring at least one order line, might need transaction-level application logic or a deferred database constraint rather than a simple foreign key.

    Strong Entities

    A strong entity can be uniquely identified using its own key and does not depend on another entity for identity.

    Strong entities:
    
    - Customer
    - Product
    - Employee
    - Course
    - Warehouse
    CREATE TABLE products
    (
        product_id BIGINT PRIMARY KEY,
        product_code VARCHAR(30) NOT NULL UNIQUE,
        product_name VARCHAR(200) NOT NULL
    );

    Weak Entities

    A weak entity depends on another entity for identification or existence.

    Order Line Example

    Order ORD-9001
    
    Line 1
    Line 2
    Line 3
    
    
    Line number 1 is unique only
    within order ORD-9001.
    CREATE TABLE order_lines
    (
        order_id BIGINT NOT NULL,
        line_number INT NOT NULL,
        product_id BIGINT NOT NULL,
        quantity INT NOT NULL,
        unit_price DECIMAL(18, 2) NOT NULL,
    
        PRIMARY KEY
        (
            order_id,
            line_number
        ),
    
        CONSTRAINT fk_order_lines_order
            FOREIGN KEY (order_id)
            REFERENCES orders (order_id),
    
        CONSTRAINT fk_order_lines_product
            FOREIGN KEY (product_id)
            REFERENCES products (product_id)
    );

    The complete identity of an order line contains the parent order key and the line's partial key.

    Supertype and Subtype Entities

    A supertype stores attributes shared by several related entity subtypes.

    Payment
       |
       +-- Card Payment
       |
       +-- Bank Transfer
       |
       +-- Wallet Payment

    Shared payment attributes can include:

    • Payment ID
    • Amount
    • Currency
    • Status
    • Created time

    Subtype-specific attributes can include a card-provider reference, bank transfer reference, or wallet provider.

    Table-per-subtype Example

    CREATE TABLE payments
    (
        payment_id BIGINT PRIMARY KEY,
        payment_type VARCHAR(30) NOT NULL,
        amount DECIMAL(18, 2) NOT NULL,
        currency CHAR(3) NOT NULL,
        payment_status VARCHAR(30) NOT NULL
    );
    
    CREATE TABLE card_payments
    (
        payment_id BIGINT PRIMARY KEY,
        provider_reference VARCHAR(100) NOT NULL,
        card_brand VARCHAR(30) NOT NULL,
    
        CONSTRAINT fk_card_payments_payment
            FOREIGN KEY (payment_id)
            REFERENCES payments (payment_id)
    );
    
    CREATE TABLE bank_transfers
    (
        payment_id BIGINT PRIMARY KEY,
        transfer_reference VARCHAR(100) NOT NULL,
    
        CONSTRAINT fk_bank_transfers_payment
            FOREIGN KEY (payment_id)
            REFERENCES payments (payment_id)
    );

    Entity-Relationship Diagrams

    An Entity-Relationship Diagram, commonly abbreviated as ERD, visually represents entities, attributes, keys, and relationships.

    Common diagram elements include:

    • Entity boxes
    • Attribute lists
    • Primary-key indicators
    • Foreign-key indicators
    • Relationship lines
    • Cardinality markers
    • Optionality markers

    Textual ER Diagram

    CUSTOMER
    --------
    PK customer_id
       display_name
       email_address
    
           1
           |
           | places
           |
           N
    
    ORDER
    -----
    PK order_id
    FK customer_id
       order_status
       created_at
    
           1
           |
           | contains
           |
           N
    
    ORDER_LINE
    ----------
    PK, FK order_id
    PK     line_number
    FK     product_id
           quantity
           unit_price
    
           N
           |
           | references
           |
           1
    
    PRODUCT
    -------
    PK product_id
       product_name
       current_price

    Conceptual, Logical, and Physical Models

    Model Level Purpose Typical Content
    Conceptual model Describes major business concepts and connections Customer places Order
    Logical model Defines detailed entities, attributes, keys, and cardinalities Customer ID, Order ID, relationship constraints
    Physical model Defines implementation for a selected database platform Tables, columns, data types, indexes, and constraints
    Data-modeling Flow
    business requirements → conceptual model → logical model → physical schema → validation and testing

    Discover Entities from Requirements

    Consider the following business requirements:

    A customer can place several orders.
    
    Every order contains one or more order lines.
    
    Each order line references one product.
    
    An order can have several payments.
    
    A payment belongs to one order.
    
    An order can create several shipments.

    Candidate Entities

    • Customer
    • Order
    • Order Line
    • Product
    • Payment
    • Shipment

    Candidate Relationships

    • Customer places Order
    • Order contains Order Line
    • Order Line references Product
    • Order has Payment
    • Order creates Shipment

    Naming Entities and Relationships

    Use clear and consistent domain terminology.

    Recommended Entity Names

    Customer
    Order
    Order Line
    Product
    Payment
    Shipment

    Recommended Relationship Names

    Customer places Order.
    
    Order contains Order Line.
    
    Order Line references Product.
    
    Order receives Payment.
    
    Order produces Shipment.

    Avoid technical names that expose temporary implementation details when a stable domain term is available.

    Translating Entities into Tables

    Conceptual Element Relational Implementation
    Entity type Table
    Entity instance Row
    Attribute Column
    Identifier Primary or unique key
    One-to-many relationship Foreign key on the many side
    Many-to-many relationship Junction table containing foreign keys
    Mandatory participation Non-nullable foreign key or another constraint
    One-to-one relationship Unique foreign key or shared primary key

    Complete Order-model Example

    CREATE TABLE customers
    (
        customer_id BIGINT PRIMARY KEY,
        customer_number VARCHAR(30) NOT NULL UNIQUE,
        display_name VARCHAR(200) NOT NULL,
        email_address VARCHAR(254) NOT NULL,
        customer_status VARCHAR(30) NOT NULL,
        created_at TIMESTAMP NOT NULL
    );
    
    CREATE TABLE products
    (
        product_id BIGINT PRIMARY KEY,
        product_code VARCHAR(30) NOT NULL UNIQUE,
        product_name VARCHAR(200) NOT NULL,
        current_price DECIMAL(18, 2) NOT NULL,
        product_status VARCHAR(30) NOT NULL
    );
    
    CREATE TABLE orders
    (
        order_id BIGINT PRIMARY KEY,
        order_number VARCHAR(30) NOT NULL UNIQUE,
        customer_id BIGINT NOT NULL,
        order_status VARCHAR(30) NOT NULL,
        ordered_at TIMESTAMP NOT NULL,
        total_amount DECIMAL(18, 2) NOT NULL,
        currency CHAR(3) NOT NULL,
    
        CONSTRAINT fk_orders_customer
            FOREIGN KEY (customer_id)
            REFERENCES customers (customer_id)
    );
    
    CREATE TABLE order_lines
    (
        order_id BIGINT NOT NULL,
        line_number INT NOT NULL,
        product_id BIGINT NOT NULL,
        product_description VARCHAR(200) NOT NULL,
        quantity INT NOT NULL,
        unit_price DECIMAL(18, 2) NOT NULL,
    
        PRIMARY KEY
        (
            order_id,
            line_number
        ),
    
        CONSTRAINT fk_order_lines_order
            FOREIGN KEY (order_id)
            REFERENCES orders (order_id),
    
        CONSTRAINT fk_order_lines_product
            FOREIGN KEY (product_id)
            REFERENCES products (product_id)
    );
    
    CREATE TABLE payments
    (
        payment_id BIGINT PRIMARY KEY,
        order_id BIGINT NOT NULL,
        payment_status VARCHAR(30) NOT NULL,
        payment_amount DECIMAL(18, 2) NOT NULL,
        currency CHAR(3) NOT NULL,
        created_at TIMESTAMP NOT NULL,
    
        CONSTRAINT fk_payments_order
            FOREIGN KEY (order_id)
            REFERENCES orders (order_id)
    );
    
    CREATE TABLE shipments
    (
        shipment_id BIGINT PRIMARY KEY,
        order_id BIGINT NOT NULL,
        shipment_status VARCHAR(30) NOT NULL,
        tracking_number VARCHAR(100) NULL,
        dispatched_at TIMESTAMP NULL,
        delivered_at TIMESTAMP NULL,
    
        CONSTRAINT fk_shipments_order
            FOREIGN KEY (order_id)
            REFERENCES orders (order_id)
    );

    Historical Snapshot Attributes

    A relationship can require transaction-time attributes instead of always reading current values from a related entity.

    Product current price:
    
    USD 90.00
    
    
    Order placed earlier:
    
    Unit price paid:
    USD 75.00
    
    
    Requirement:
    
    The historical order must continue to show
    the transaction-time price.

    Therefore, the order line stores a product reference and a snapshot of the description and price used for that transaction.

    Historical rule: Foreign keys preserve identity relationships, but transactional records can also require copied snapshot attributes that must not change with the current parent entity.

    Query Related Entities

    Customers and Orders

    SELECT
        c.customer_number,
        c.display_name,
        o.order_number,
        o.order_status,
        o.ordered_at
    FROM customers AS c
    INNER JOIN orders AS o
        ON o.customer_id = c.customer_id
    ORDER BY
        c.customer_number,
        o.ordered_at DESC;

    Order Details

    SELECT
        o.order_number,
        ol.line_number,
        ol.product_description,
        ol.quantity,
        ol.unit_price,
        ol.quantity * ol.unit_price
            AS line_amount
    FROM orders AS o
    INNER JOIN order_lines AS ol
        ON ol.order_id = o.order_id
    WHERE
        o.order_number = :order_number
    ORDER BY
        ol.line_number;

    Customers without Orders

    SELECT
        c.customer_number,
        c.display_name
    FROM customers AS c
    LEFT JOIN orders AS o
        ON o.customer_id = c.customer_id
    WHERE
        o.order_id IS NULL;

    Referential Integrity

    Referential integrity ensures that foreign-key values refer to valid parent rows or are null when the relationship is optional.

    Invalid relationship:
    
    Order customer_id = 999
    
    No customer 999 exists.
    
    
    Foreign-key result:
    
    Database rejects the order insert
    or update.

    Foreign keys help prevent:

    • Orders referring to nonexistent customers
    • Order lines referring to nonexistent orders
    • Payments referring to nonexistent orders
    • Memberships referring to nonexistent users or projects
    • Orphaned child records

    Delete and Update Actions

    A foreign-key relationship needs an explicit policy for parent deletion and key changes.

    Action Meaning Use Carefully When
    RESTRICT or NO ACTION Rejects the parent change when dependent rows exist Child records must be handled explicitly
    CASCADE Propagates the parent deletion or key update Children have no meaning without the parent
    SET NULL Removes the relationship while preserving the child row The relationship is genuinely optional
    SET DEFAULT Replaces the foreign key with a configured default The database and domain define a valid default relationship

    Deletion warning: Do not apply cascading deletion automatically merely for convenience. Confirm that deleting every dependent entity is correct for the business, audit, legal, and historical requirements.

    Relationship Constraints

    Foreign keys alone do not express every business rule.

    Additional relationship rules can include:

    • An order must contain at least one line
    • One address must be the customer's primary address
    • A user cannot join the same project twice
    • A shipment cannot belong to a cancelled order
    • A manager cannot report directly or indirectly to the same employee
    • A payment currency must match the order currency
    • One active profile can exist for each user

    These rules can require unique constraints, check constraints, transactions, deferred validation, triggers, or application services.

    Relationship Lifecycle

    Relationships can change over time and can require history.

    Employment Assignment

    Employee assigned to Department A:
    
    Start: 2025-01-01
    End:   2026-03-31
    
    
    Employee assigned to Department B:
    
    Start: 2026-04-01
    End:   null
    CREATE TABLE employee_department_assignments
    (
        assignment_id BIGINT PRIMARY KEY,
        employee_id BIGINT NOT NULL,
        department_id BIGINT NOT NULL,
        valid_from DATE NOT NULL,
        valid_to DATE NULL,
    
        FOREIGN KEY (employee_id)
            REFERENCES employees (employee_id),
    
        FOREIGN KEY (department_id)
            REFERENCES departments (department_id),
    
        CONSTRAINT ck_assignment_dates
            CHECK
            (
                valid_to IS NULL
                OR valid_to >= valid_from
            )
    );

    Replacing the current department foreign key on the employee row would lose historical assignment information.

    Temporal Relationships

    A temporal relationship records when an association is valid.

    Examples include:

    • Employee department assignments
    • Product category memberships
    • Customer subscription plans
    • Contract assignments
    • Resource ownership
    • Price agreements

    The model should define whether overlapping validity periods are allowed and how the current relationship is determined.

    Avoid Storing Sensitive Relationships Unnecessarily

    A relationship can reveal sensitive business or personal information even when its individual entity attributes appear harmless.

    Apply:

    • Data minimization
    • Purpose limitation
    • Access control
    • Retention policies
    • Audit logging
    • Encryption where required

    Do not expose relationship tables directly through an API without authorization and a clear client-facing contract.

    Entity-discovery Workflow

    1. Gather business use cases and data requirements.
    2. Identify important nouns as candidate entities.
    3. Identify verbs as candidate relationships.
    4. Define one stable identifier for each entity.
    5. List attributes and their business meanings.
    6. Define relationship cardinality.
    7. Define mandatory and optional participation.
    8. Resolve many-to-many relationships with associative entities.
    9. Identify weak entities and ownership dependencies.
    10. Identify historical and temporal relationships.
    11. Validate the model using realistic business scenarios.
    12. Translate the logical model into a physical relational schema.

    Modeling Review Questions

    • Can every entity instance be uniquely identified?
    • Does every attribute describe the correct entity?
    • Are multi-valued attributes modeled separately?
    • Are cardinalities based on real business rules?
    • Is optionality represented correctly?
    • Are many-to-many relationships resolved?
    • Do relationship attributes belong in an associative entity?
    • Are historical snapshots preserved where necessary?
    • Are deletion rules safe?
    • Can foreign keys prevent invalid references?
    • Are sensitive relationships protected?
    • Can the model support the required queries?

    Common Entity and Relationship Mistakes

    1

    Creating Tables before Understanding the Domain

    Starting with columns can produce a schema that does not represent the actual business concepts and rules.

    2

    Treating Every Noun as an Entity

    Some nouns are attributes, values, or temporary implementation details rather than independently identifiable entities.

    3

    Storing Several Values in One Column

    Comma-separated lists are difficult to validate, reference, index, and query relationally.

    4

    Leaving Relationships without Foreign Keys

    Application code alone might not prevent invalid or orphaned references.

    5

    Implementing Many-to-many Relationships Directly

    Relational databases normally require a junction table containing the participating foreign keys.

    6

    Ignoring Relationship Attributes

    Enrollment date, membership role, quantity, or agreed price can belong to the relationship rather than either participating entity.

    7

    Using Nullable Foreign Keys without Business Meaning

    Optional relationships should be intentional and documented rather than introduced to bypass validation.

    8

    Using Cascade Delete without Impact Analysis

    Cascading deletion can remove important historical or dependent records unexpectedly.

    9

    Using Mutable Attributes as Stable Identifiers

    Email addresses, names, and telephone numbers can change and are often unsuitable as permanent relationship keys.

    10

    Losing Historical Relationships

    Replacing one current foreign key can erase information about previous assignments, memberships, prices, or ownership.

    11

    Duplicating Current Data instead of Referencing It

    Uncontrolled duplication can produce inconsistent values. Duplicate data only when the model requires a historical snapshot or deliberate denormalization.

    12

    Assuming the Diagram Enforces the Rules

    An ER diagram documents intent. The physical schema and application must implement the required keys, constraints, transactions, and policies.

    Recommended Test Cases

    Test Expected Evidence
    Unique entity identity Duplicate primary and candidate keys are rejected
    Valid parent relationship A child can reference an existing parent
    Missing parent A foreign key prevents an invalid reference
    Mandatory relationship A required foreign key cannot be null
    Optional relationship A valid child can exist without the optional parent reference
    One-to-one relationship A uniqueness constraint prevents a second related child
    Many-to-many relationship The junction table supports several entities on both sides
    Duplicate relationship A unique or composite key prevents duplicate association rows
    Weak entity The child cannot exist without its identifying parent
    Historical relationship Previous assignment periods remain available after a change
    Parent deletion The configured restriction, cascade, or nullification policy is applied
    Relationship query Joins return the expected related entity instances

    Entities and Relationships Best Practices

    Recommended Practices

    • Begin with business requirements rather than database tables.
    • Model stable domain concepts as entities.
    • Give every entity a reliable identifier.
    • Define every attribute's type, meaning, and nullability.
    • Separate multi-valued attributes into related entities.
    • Define relationship names in clear business language.
    • Document minimum and maximum cardinality.
    • Represent mandatory participation through appropriate constraints.
    • Place a foreign key on the many side of a one-to-many relationship.
    • Resolve many-to-many relationships through junction tables.
    • Promote relationships with attributes into associative entities.
    • Use unique constraints to enforce one-to-one relationships.
    • Use foreign keys to preserve referential integrity.
    • Review delete and update actions carefully.
    • Preserve historical relationships when required.
    • Store transaction-time snapshots where current values must not rewrite history.
    • Separate conceptual, logical, and physical design decisions.
    • Validate the model using realistic workflows and edge cases.
    • Protect sensitive entities and relationships.
    • Verify the design using constraints and automated database tests.

    Practice Exercise

    Design an entity-relationship model for an online course platform.

    Requirements

    1. A learner can enroll in several courses.
    2. A course can contain several chapters.
    3. A chapter can contain several lessons.
    4. A course can have several instructors.
    5. An instructor can teach several courses.
    6. An enrollment stores enrollment time, status, and completion percentage.
    7. A learner can attempt several quizzes.
    8. Each quiz attempt stores a score and submission time.
    9. A lesson can have several documents and videos.
    10. Each course has one category.
    11. A category can contain several courses.
    12. Historical quiz attempts must remain available.

    Candidate Entity Inventory

    Entity Identifier Important Attributes Relationships
    Learner Learner ID Name, email, status Enrollments and quiz attempts
    Course Course ID Title, description, status Category, chapters, instructors, and enrollments
    Enrollment Enrollment ID or composite key Enrolled time, status, completion Learner and course
    Chapter Chapter ID Title and display order Course and lessons
    Lesson Lesson ID Title, content type, display order Chapter, documents, and videos
    Quiz Attempt Attempt ID Score, started time, submitted time Learner and quiz

    Relationship Template

    Learner N -------- N Course
    Resolved through Enrollment
    
    Course 1 -------- N Chapter
    
    Chapter 1 -------- N Lesson
    
    Instructor N -------- N Course
    Resolved through Course Instructor
    
    Learner 1 -------- N Quiz Attempt
    
    Quiz 1 -------- N Quiz Attempt
    
    Category 1 -------- N Course

    Frequently Asked Questions

    1

    What is an entity?

    An entity is an identifiable object, event, place, person, concept, or transaction about which the system stores information.

    2

    What is an attribute?

    An attribute is a property or characteristic that describes an entity or relationship.

    3

    What is a relationship?

    A relationship is an association between instances of one or more entity types.

    4

    What is cardinality?

    Cardinality defines how many instances of one entity can be associated with instances of another entity.

    5

    What is a one-to-many relationship?

    It is a relationship in which one parent can be associated with several children while each child belongs to one parent.

    6

    How is a many-to-many relationship implemented?

    It is normally implemented through a junction table containing foreign keys referencing both participating entities.

    7

    What is an associative entity?

    An associative entity represents a relationship that has its own attributes, identity, lifecycle, or business rules.

    8

    What is a weak entity?

    A weak entity depends on another entity for its complete identity or existence.

    9

    What is a recursive relationship?

    A recursive relationship connects instances of an entity type to other instances of the same entity type.

    10

    What is participation?

    Participation defines whether an entity must be involved in a relationship or can exist without that relationship.

    11

    What is the difference between an ER model and a relational schema?

    An ER model conceptually describes entities, attributes, and relationships. A relational schema implements the model using tables, columns, keys, and constraints.

    12

    What comes after entities and relationships?

    The next topic is normalization and denormalization, followed by keys and constraints.

    Key Takeaway

    Entities represent identifiable domain concepts, attributes describe those entities, and relationships define how entity instances are associated. Model one-to-one relationships with uniqueness, one-to-many relationships with foreign keys on the many side, and many-to-many relationships through associative tables. Define cardinality, optionality, identifiers, referential integrity, delete behaviour, historical relationships, and transaction-time snapshots explicitly. Begin with a conceptual business model, refine it into a logical design, and translate it into a physical schema containing suitable tables, keys, constraints, and data types.