AlgoPlusAlgoPlus
Learn/Databases
Lesson

ER Model

Sketch a domain as entities, attributes, and relationships — then mechanically turn the diagram into relational tables.

9 min read Watch it move Build it

The entity-relationship (ER) model is a picture of your data *before any tables exist*. You draw the real-world things you care about — entities — as rectangles, the facts about them — attributes — as ovals, and the meaningful links between them — relationships — as diamonds. It is a design-time sketch. A mechanical recipe then turns that diagram into actual tables, which is why join tables appear seemingly from nowhere.

The three building blocks

  1. 1Entity — a thing the database keeps data about, drawn as a rectangle. The whole collection is an *entity set* (e.g. all Students).
  2. 2Attribute — a fact stored about an entity, drawn as an oval (a student's name, age). The key attribute — the one that tells each entity apart — is underlined (a student_id).
  3. 3Relationship — a link between entities, drawn as a diamond (Student *enrolls in* Course). It can carry its own attributes that belong to the pairing, like the grade.
Cardinality is the crucial label
Every relationship is tagged with how many of one side may link to the other: 1:1, 1:N (one-to-many), or M:N (many-to-many). This single number decides how the relationship becomes tables.

A worked example — a university

Two entities: Student (key student_id, plus name) and Course (key course_code, plus title). One relationship: Enrolls, which is M:N (a student takes many courses, a course has many students) and carries its own attribute grade. Here is the mechanical mapping to tables.

-- Each entity becomes its own table; the key attribute becomes the primary key
CREATE TABLE Student (
  student_id  INT PRIMARY KEY,
  name        VARCHAR(60)
);
CREATE TABLE Course (
  course_code VARCHAR(8) PRIMARY KEY,
  title       VARCHAR(80)
);

-- An M:N relationship becomes its OWN table of foreign keys,
-- plus any attributes that belonged to the relationship itself
CREATE TABLE Enrolls (
  student_id  INT     REFERENCES Student(student_id),
  course_code VARCHAR(8) REFERENCES Course(course_code),
  grade       CHAR(1),
  PRIMARY KEY (student_id, course_code)
);
The mapping recipe
Entities → one table each, key attribute → primary key. 1:N relationship → put the 'one' side's key as a foreign key on the 'many' side's table (no new table). M:N relationship → a brand-new table holding both foreign keys plus the relationship's own attributes.
OperationTimeSpace
Entity · rectangle becomes a relation→ 1 tablekey → primary key
1:N relationship · FK on the 'many' side→ FK columnno new table
M:N relationship · the join table→ new tabletwo FKs + attrs
Check yourself
In the university example, why does the Enrolls relationship become its own separate table instead of a foreign key column?