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.
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
| Concept | Meaning | Notation (Chen) | Example |
|---|---|---|---|
| Entity | a distinguishable "thing" | rectangle | Customer, Order |
| Entity set | all entities of one type | — | all customers |
| Attribute | a property | oval | name, email |
| Key attribute | uniquely identifies an entity | underlined oval | customer_id |
| Relationship | association between entities | diamond | Customer places Order |
| Weak entity | identified only via an owner | double rectangle | OrderLine |
Attribute types
| Type | Description | Example | Mapping to tables |
|---|---|---|---|
| Simple | atomic | age | one column |
| Composite | made of parts | address (street, city, zip) | one column per part |
| Multivalued | many values per entity | phone_numbers | separate table (customer_id, phone) |
| Derived | computed from others | age from date_of_birth | usually not stored (or a generated column) |
| Single vs nullable | may be absent | middle_name | nullable 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
In practice most teams draw crow's foot notation (used by dbdiagram, Lucidchart, ERD tools):
| Symbol at the line end | Meaning |
|---|---|
|| | 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
CarandTruckup intoVehicle. - Specialisation: split
AccountintoSavingsAccountandCheckingAccount. - 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 construct | Relational mapping |
|---|---|
| Strong entity | table; key attribute → primary key |
| Composite attribute | one column per component |
| Multivalued attribute | new table (owner_key, value), PK on both |
| Weak entity | table with PK = owner PK + partial key; FK to owner ON DELETE CASCADE |
| 1:1 relationship | FK on either side (prefer the side with total participation) + UNIQUE |
| 1:N relationship | FK on the N side |
| M:N relationship | junction table with both FKs as a composite PK + relationship attributes |
| Ternary relationship | table with three FKs |
| Recursive relationship | FK to the same table (manager_id → employee.id) |
| ISA hierarchy | single 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.
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_centslives 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.
lessonuses a surrogate key solesson_progresshas a short FK, whileUNIQUEpreserves 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,Instructortables duplicatingUser) instead of roles/relationships on oneUser. - Ignoring cardinality edge cases ("can an order have zero items?", "can a user have two accounts with one email?").
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.