06 / 32 · 4 min
From a drawing to tables
The ER diagram becomes tables by a small set of rules that never change.
Every entity becomes a table. Its attributes become columns; its key becomes the primary key.
One-to-many becomes a foreign key on the MANY side. A department has many students, so students carries dept_id. Putting it the other way round would need one column per student.
Many-to-many becomes a table. Its primary key is the pair of foreign keys, which enforces "at most once" for free:
CREATE TABLE enrolment (
roll_no INT REFERENCES students(roll_no),
course_code VARCHAR(8) REFERENCES courses(code),
enrolled_on DATE NOT NULL,
grade CHAR(2),
PRIMARY KEY (roll_no, course_code)
);A multivalued attribute becomes a table. A student with several phone numbers does not get phone1, phone2, phone3: that fixes a maximum, wastes space, and makes "who has this number?" search three columns. It gets a student_phones table.
A weak entity takes its owner's key. Beds numbered 1, 2, 3 within each room have primary key (room_id, bed_no).
Takeaway: the rules are mechanical. If a mapping feels like it needs cleverness, the diagram is usually wrong.