Designing Entity-Relationship Models

1. Identifying Entities and Attributes

ConceptDefinitionExample
EntityReal-world object/concept stored as tableCustomer, Order, Product
Entity SetCollection of similar entitiesAll customers
AttributeProperty describing an entityname, email, price
Simple AttributeAtomic, indivisibleage, status
Composite AttributeDecomposable into sub-partsaddress (street, city, zip)
Derived AttributeComputed from othersage from birthdate
Multi-valuedMultiple values per entityphone_numbers

2. Defining Primary Keys

Key TypeDescriptionExample
Primary KeyUnique + NOT NULL identifierid BIGSERIAL PRIMARY KEY
Surrogate KeySystem-generated (auto-increment, UUID)UUID DEFAULT gen_random_uuid()
Natural KeyReal-world unique attributeSSN, ISBN, email
Composite KeyMultiple columns combinedPRIMARY KEY(order_id, line_no)
Candidate KeyAny valid unique identifieremail OR phone OR id
Alternate KeyCandidate not chosen as PKemail (when id is PK)
Note: Prefer surrogate keys (UUID v7 or BIGSERIAL) for stability — natural keys can change.

3. Establishing Relationships

RelationshipCardinalityImplementation
One-to-One (1:1)Each A maps to one BFK with UNIQUE constraint
One-to-Many (1:N)Each A relates to many BFK on the many side
Many-to-Many (M:N)Many A to many BJunction/associative table
Unary (Recursive)Entity relates to itselfFK referencing same table

Example: M:N via Junction Table

CREATE TABLE students (id BIGSERIAL PRIMARY KEY, name TEXT);
CREATE TABLE courses  (id BIGSERIAL PRIMARY KEY, title TEXT);
CREATE TABLE enrollments (
  student_id BIGINT REFERENCES students(id) ON DELETE CASCADE,
  course_id  BIGINT REFERENCES courses(id)  ON DELETE CASCADE,
  enrolled_at TIMESTAMPTZ DEFAULT NOW(),
  PRIMARY KEY (student_id, course_id)
);

4. Understanding Cardinality and Participation

NotationMeaning
1..1Exactly one (mandatory)
0..1Zero or one (optional)
1..*One or more (mandatory many)
0..*Zero or more (optional many)
Total ParticipationEvery entity must participate (double line)
Partial ParticipationSome entities may not participate (single line)

5. Creating ER Diagrams

SymbolMeaning
RectangleEntity
Double RectangleWeak entity
DiamondRelationship
OvalAttribute
Underlined OvalPrimary key attribute
Dashed OvalDerived attribute
Double OvalMulti-valued attribute
Crow's FootMany side of relationship
  ┌──────────┐         ┌──────────┐         ┌──────────┐
  │ Customer │1───────∞│  Order   │∞───────∞│ Product  │
  └──────────┘ places  └──────────┘contains └──────────┘
       │ id (PK)            │ id (PK)            │ id (PK)
       │ email              │ customer_id (FK)   │ name
       │ name               │ placed_at          │ price
        

6. Handling Weak Entities and Identifying Relationships

ConceptDescription
Weak EntityHas no PK of its own; depends on owner
Identifying RelationshipConnects weak entity to its owner
Partial Key (Discriminator)Distinguishes weak entity within owner
Composite PKowner_pk + partial_key

Example: Weak Entity (OrderItem)

CREATE TABLE order_items (
  order_id   BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
  line_no    INT    NOT NULL,           -- partial key
  product_id BIGINT NOT NULL REFERENCES products(id),
  qty        INT    NOT NULL,
  PRIMARY KEY (order_id, line_no)        -- composite identifier
);

7. Modeling Recursive Relationships

PatternExample
Self-FKemployee.manager_id → employee.id
Bill of Materialspart contains parts (M:N self)
Category Treecategory.parent_id → category.id

Example: Employee-Manager

CREATE TABLE employees (
  id         BIGSERIAL PRIMARY KEY,
  name       TEXT NOT NULL,
  manager_id BIGINT REFERENCES employees(id)
);

8. Using Associative Entities

When to UseReason
M:N with attributesJunction table needs columns (e.g., enrolled_at, grade)
Ternary relationships3+ entities participate (Doctor-Patient-Hospital)
Historical trackingEach association needs timestamp/audit

9. Defining Attribute Types

TypeDescriptionExample
SimpleAtomic valueage, status
CompositeDecomposablefull_name → first/last
Single-valuedOne value per entitybirth_date
Multi-valuedMultiple valuesphones, tags
StoredPersisted on diskprice
DerivedComputedtotal = price * qty
Key AttributeUniquely identifies entityid, ssn

10. Modeling Generalization and Specialization

StrategyTablesTrade-off
Single Table InheritanceOne table + type columnSimple, but many NULLs
Class Table InheritanceParent + child tables with FKNormalized, requires joins
Concrete Table InheritanceOne table per concrete subclassNo joins, schema duplication
GeneralizationBottom-up: combine subclassesFind common attributes
SpecializationTop-down: split into subclassesDistinguish by role/type

Example: Class Table Inheritance

CREATE TABLE person (
  id    BIGSERIAL PRIMARY KEY,
  name  TEXT NOT NULL,
  email TEXT UNIQUE
);
CREATE TABLE employee (
  id     BIGINT PRIMARY KEY REFERENCES person(id) ON DELETE CASCADE,
  salary NUMERIC(10,2)
);
CREATE TABLE customer (
  id          BIGINT PRIMARY KEY REFERENCES person(id) ON DELETE CASCADE,
  loyalty_pts INT DEFAULT 0
);