{}DSA Atlas

ER Modelling

Entities, attributes (simple, composite, multivalued, derived), relationships, cardinality and participation, weak entities, specialisation/generalisation, and the step-by-step mapping from an ER diagram to relational tables — with a full worked example.

Beginner6 interview questions

Why model first?

Tables are an implementation; the domain comes first. An ER (Entity–Relationship) model, introduced by Peter Chen in 1976, captures what we store and how things relate — before deciding how to store it. A good conceptual model makes the schema almost write itself and prevents the most expensive kind of bug: a wrong data model discovered after launch.

Building blocks

ConceptMeaningNotation (Chen)Example
Entitya distinguishable "thing"rectangleCustomer, Order
Entity setall entities of one type—all customers
Attributea propertyovalname, email
Key attributeuniquely identifies an entityunderlined ovalcustomer_id
Relationshipassociation between entitiesdiamondCustomer places Order
Weak entityidentified only via an ownerdouble rectangleOrderLine

Attribute types

TypeDescriptionExampleMapping to tables
Simpleatomicageone column
Compositemade of partsaddress (street, city, zip)one column per part
Multivaluedmany values per entityphone_numbersseparate table (customer_id, phone)
Derivedcomputed from othersage from date_of_birthusually not stored (or a generated column)
Single vs nullablemay be absentmiddle_namenullable column

Relationships

Degree

  • Unary (recursive): Employee manages Employee.
  • Binary: Customer places Order (most common).
  • Ternary: Doctor prescribes Drug to Patient — can't always be decomposed into binaries without losing meaning.

Cardinality and participation

Person has Passport 11 1:1 Customer places Order 1N 1:N — every Order must havea Customer (double line = total) Student enrols Course MN M:N — needs a junction table;"grade" lives on the relationship
Chen-style notation for the three cardinalities.

In practice most teams draw crow's foot notation (used by dbdiagram, Lucidchart, ERD tools):

Symbol at the line endMeaning
||exactly one
o|zero or one
|< (crow's foot with bar)one or many
o< (crow's foot with circle)zero or many

Weak entities

An OrderLine has no identity without its Order: its key is (order_id, line_no). Weak entities have total participation in their identifying relationship and are typically deleted with the owner.

Specialisation and generalisation (ISA)

  • Generalisation: pull common attributes of Car and Truck up into Vehicle.
  • Specialisation: split Account into SavingsAccount and CheckingAccount.
  • Constraints: disjoint vs overlapping (can an entity be in two subclasses?), total vs partial (must every entity be in some subclass?).

Mapping ER to relational tables

ER constructRelational mapping
Strong entitytable; key attribute → primary key
Composite attributeone column per component
Multivalued attributenew table (owner_key, value), PK on both
Weak entitytable with PK = owner PK + partial key; FK to owner ON DELETE CASCADE
1:1 relationshipFK on either side (prefer the side with total participation) + UNIQUE
1:N relationshipFK on the N side
M:N relationshipjunction table with both FKs as a composite PK + relationship attributes
Ternary relationshiptable with three FKs
Recursive relationshipFK to the same table (manager_id → employee.id)
ISA hierarchysingle table, class table (joined), or concrete table — see the questions below

Worked example: an online course platform

Requirements

  • Users sign up with a unique email; a user can be a student, an instructor, or both.
  • Instructors create courses; a course has exactly one owning instructor and many co-instructors.
  • A course has ordered sections, each with ordered lessons (video or article).
  • Students enrol in courses (paying a price that can differ from today's list price) and track lesson progress.
  • Students can review a course once (1–5 stars, text).

Entities: User, Course, Section (weak: owned by Course), Lesson (weak: owned by Section), Enrolment (relationship with attributes), Review, LessonProgress.

SQL
CREATE TABLE app_user (
    id            BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email         TEXT NOT NULL UNIQUE,
    display_name  TEXT NOT NULL,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE course (
    id             BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    owner_id       BIGINT NOT NULL REFERENCES app_user(id),      -- 1:N, total participation
    title          TEXT NOT NULL,
    list_price_cents INT NOT NULL CHECK (list_price_cents >= 0),
    published_at   TIMESTAMPTZ
);

CREATE TABLE course_instructor (                                   -- M:N co-instructors
    course_id BIGINT REFERENCES course(id) ON DELETE CASCADE,
    user_id   BIGINT REFERENCES app_user(id),
    PRIMARY KEY (course_id, user_id)
);

CREATE TABLE section (                                             -- weak entity
    course_id BIGINT REFERENCES course(id) ON DELETE CASCADE,
    position  INT NOT NULL,
    title     TEXT NOT NULL,
    PRIMARY KEY (course_id, position)
);

CREATE TABLE lesson (
    id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,   -- surrogate key: simpler FKs
    course_id  BIGINT NOT NULL,
    section_pos INT NOT NULL,
    position   INT NOT NULL,
    kind       TEXT NOT NULL CHECK (kind IN ('video', 'article')),
    title      TEXT NOT NULL,
    video_url  TEXT,
    body       TEXT,
    FOREIGN KEY (course_id, section_pos) REFERENCES section(course_id, position) ON DELETE CASCADE,
    UNIQUE (course_id, section_pos, position),
    CHECK ((kind = 'video' AND video_url IS NOT NULL) OR (kind = 'article' AND body IS NOT NULL))
);

CREATE TABLE enrolment (                                           -- M:N with attributes
    user_id     BIGINT REFERENCES app_user(id),
    course_id   BIGINT REFERENCES course(id),
    paid_cents  INT NOT NULL,                                      -- price at purchase time
    enrolled_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (user_id, course_id)
);

CREATE TABLE lesson_progress (
    user_id      BIGINT,
    lesson_id    BIGINT REFERENCES lesson(id) ON DELETE CASCADE,
    completed_at TIMESTAMPTZ,
    PRIMARY KEY (user_id, lesson_id)
);

CREATE TABLE review (
    user_id   BIGINT,
    course_id BIGINT,
    stars     SMALLINT NOT NULL CHECK (stars BETWEEN 1 AND 5),
    body      TEXT,
    PRIMARY KEY (user_id, course_id),                              -- "once per course"
    FOREIGN KEY (user_id, course_id) REFERENCES enrolment(user_id, course_id)  -- only enrolled users
);

Design decisions worth saying out loud in an interview:

  • paid_cents lives on enrolment, not course — it's a fact about the purchase (historical price).
  • The "review only if enrolled" rule is enforced by a composite FK to enrolment rather than application code.
  • lesson uses a surrogate key so lesson_progress has a short FK, while UNIQUE preserves the natural ordering key.
  • Polymorphic lesson types use a single table + CHECK because they share nearly everything.

Common modelling mistakes

  • Storing lists in a column ("tag1,tag2") instead of a child table (or a typed array/JSON when you never query by element).
  • Putting relationship attributes on an entity (price on product instead of order line).
  • Missing the history dimension: if something changes and you need the old value (prices, addresses on orders), copy it at the time of the event.
  • Modelling roles as separate entities (Student, Instructor tables duplicating User) instead of roles/relationships on one User.
  • Ignoring cardinality edge cases ("can an order have zero items?", "can a user have two accounts with one email?").

Interview questions

0 / 6 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.