…
…
SQL and Database Fundamentals · Lesson 31 / 41 · Data modeling
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Student Affairs wants to grow the club system: clubs will have events, students will join clubs and attend events, and every club will have a president. In the last three lessons you built tables one by one, added rules, and connected them. In this lesson you will draw the model of the whole system before you write a single table.
The request from Student Affairs is a text of five sentences:
It is tempting to start writing CREATE TABLE straight from this text. But when you write the first table you make a decision (where do I put membership?), and by the third table you notice that the decision was wrong. Now you have to tear down tables that already hold data and build them again. Data modeling is the planning work you do on paper before you turn a real system into tables: which things will you keep information about, which properties does each one have, and how do they connect? A bad model gets expensive later: the same information repeats in many places, some relationships cannot be built at all, and some questions stay unanswered.
In this lesson you will:
The most common modeling method is the entity-relationship model (ER for short). It has three parts:
There is an easy way to find them in a scenario text: nouns usually give you entities or attributes, and verbs give you relationships. Read the text once more and imagine underlining the nouns in one color and the verbs in another.
Example 1 (case): Reading the club scenario
| Word in the text | Type | Role in the model |
|---|---|---|
| student, club, event | noun | entity (table) |
| name, founding date, title, date | noun | attribute (column) |
| joins | verb | relationship: student - club |
| organizes | verb | relationship: club - event |
| attends | verb | relationship: student - event |
| has a president | verb | relationship: club - student (president) |
| role | noun | attribute of a relationship (see below) |
"University" is also a noun, but it is not a table: it is the system we are modeling. In a database built for a single university, a "university" table would have one row and no purpose. Not every noun is a table. A noun is an entity only if you will keep many records about it and it has attributes of its own. "Name" and "date" are not things on their own; they are properties of something else, so they are attributes. There is also "role". You will see in a moment where it belongs, because it is a property of neither the student nor the club.
Match each word in the club scenario with its role in the model.
For each row, pick its match from the list, then check.
Let's try the same method outside school. The scenario is: "In a recipe app, users write recipes; every recipe has ingredients and amounts; users rate recipes." Count the nouns: user, recipe, ingredient, amount, rating. Are they all tables?
How many entities (things that become tables) are in the recipe scenario?
You will build the full model of this scenario yourself in the first exercise.
Finding a relationship is not enough. You also need its cardinality: how many records on the other side can one record on this side match? The only reliable way to find it is to ask about the relationship from both directions:
If one direction says "many" and the other says "one", the relationship is one-to-many (1-N). If both directions say "many", it is many-to-many (N-M). If both say "one", it is one-to-one (1-1). In lesson 14 you told these types apart by looking at data and counting. Here the direction flips: there is no data yet, only a sentence, and you build the model from the sentence. Each type has a fixed rule for turning into tables:
| Relationship | Example | How it becomes tables |
|---|---|---|
| One-to-many (1-N) | Club → events | Foreign key on the "many" side: event.club_id |
| Many-to-many (N-M) | Students ↔ clubs | Junction table: club_member (student_id, club_id), two foreign keys, composite primary key |
| One-to-one (1-1) | Club → president | Foreign key + UNIQUE: president.student_id UNIQUE |
In a one-to-many relationship, the foreign key always goes on the "many" side. The reason is simple: a column holds only one value per row. club_id in the event table points to the one club of each event, and there is no limit on how many events can point to the same club. If you put an event_id in the club table instead, every club row would have room for only one event.
"A club organizes many events, and each event is organized by one club." In which table should the foreign key go?
You can see how important it is to ask from both directions in the case database too. In lesson 14 you met the enrollment table, which connects students to sections (course_offering). What type of relationship is this?
Example: counting `enrollment` from both directions
SELECT COUNT(*) AS enrollments, COUNT(DISTINCT student_id) AS students, COUNT(DISTINCT offering_id) AS sections FROM enrollment;
| enrollments | students | sections |
|---|---|---|
| 781 | 117 | 50 |
The 781 enrollments are spread across 117 students and 50 sections, so both students and sections appear many times. If you group and count, you find that one student has at most 11 enrollments and one section has at most 79. One student, many sections; one section, many students: "many" in both directions. If you had only said "one section has many students", you would have guessed 1-N and put a single offering_id in the student table. Then every student could enroll in only one course.
Now ask the same two questions about different relationship sentences:
Ask each relationship from both directions and match it with its type.
For each row, pick its match from the list, then check.
A many-to-many relationship cannot be built directly between two tables. The best way to see why is to try it. Suppose a friend modeled membership like this: every club row gets a student_id column. For the first member there is no problem. What happens when you want to add a second member?
Example 2 (case): A wrong model with a single foreign key
CREATE TABLE club ( id INTEGER PRIMARY KEY, name VARCHAR(60) NOT NULL, student_id INTEGER REFERENCES student(id) ); INSERT INTO club VALUES (1, 'Chess', 1); INSERT INTO club VALUES (1, 'Chess', 2);
OutputERROR: duplicate key value violates unique constraint "club_pkey"You will see the row-insert command (INSERT) in detail in lesson 34. Here the ready-made rows show what the model accepts. The Chess club row has room for exactly one member, and it is taken. Writing a second member with the same id breaks the primary key. What if we give it a new id?
INSERT INTO club VALUES (1, 'Chess', 1); INSERT INTO club VALUES (2, 'Chess', 2); SELECT COUNT(*) AS row_count, COUNT(DISTINCT name) AS club_names FROM club;
| row_count | club_names |
|---|---|
| 2 | 1 |
This time there is no error, but something worse happened: one Chess club was split into two rows. The school has one club, and the table has two. If you add a founding date to the club, the two rows can hold two different dates. The question "how many clubs are there?" gets the wrong answer. A foreign key in another table that wants to point at Chess cannot know whether to point at 1 or 2.
The correct model moves the relationship into its own table, a junction table. Each row of the junction table is a single pairing: "student 1 is a member of club 1". The club stays in its own table as a single row, no matter how many members it has.
CREATE TABLE club_member ( student_id INTEGER REFERENCES student(id), club_id INTEGER REFERENCES club(id), role VARCHAR(20) NOT NULL DEFAULT 'member', PRIMARY KEY (student_id, club_id) );
The junction table has two foreign keys, and the primary key is the two together. The same student cannot join the same club twice, but the same student can connect to other clubs and the same club to other students. The enrollment table in the case database is exactly this kind of junction table; there, uniqueness is protected with UNIQUE (student_id, offering_id).
The cell below has the wrong model ready. First run it and see the club split into two rows. Then try two tasks:
1. Change the 2 in the second INSERT line to 1: try to add a second member with the same id and read the error.
2. Fix the model: drop the student_id column from the club table and add the club_member table above. Add the club as a single row (INSERT INTO club VALUES (1, 'Chess');), add two members with INSERT INTO club_member (student_id, club_id) VALUES (1, 1), (2, 1);, and make the last line SELECT * FROM club_member;.
Try it now· not graded; doesn't affect progress
In the second task you did not give a value for the role column, but SELECT * showed member in both rows: the DEFAULT from lesson 29 is at work.
Look at the role column in the club_member table. A student can be vice president in the Chess club and an ordinary member in the Robotics club. The role is not a property of the student (the student has two different roles in two clubs) and not a property of the club (each member of the club has a different role). The role belongs to that student's membership in that club. Information like this is called an attribute of a relationship, and its place is the junction table.
The case has a ready example: the midterm, final, and letter grade in the enrollment table. Think about whose grade it is. The same student has a different grade in each course, and the same course has a different grade for each student. The grade belongs to the pairing of a student and a section, so it sits in the enrollment row. The amount and the rating in the recipe scenario are the same kind of information.
Student Affairs also wants to record the date a student joined a club. In which table should this date go?
One-to-one relationships are rare. They are usually built for records that take on a role (the club's president) or for information that is filled in rarely or must be kept separate (a student's campus card). Both sides must be unique. The business rule for the president is this: every club has one president, and a student is the president of at most one club.
Example: The president table (1-1)
CREATE TABLE president ( club_id INTEGER PRIMARY KEY REFERENCES club(id), student_id INTEGER NOT NULL UNIQUE REFERENCES student(id) ); INSERT INTO club VALUES (1, 'Chess'), (2, 'Robotics'); INSERT INTO president VALUES (1, 2); INSERT INTO president VALUES (2, 2);
OutputERROR: duplicate key value violates unique constraint "president_student_id_key"Because club_id is the primary key, a club appears in the table only once: there cannot be two presidents. Because student_id is UNIQUE, student 2 could not be made president of Robotics as well. Without the UNIQUE, this table would not be 1-1. It would be a 1-N table that says "one student is president of many clubs". The name president_student_id_key in the error message is the name PostgreSQL gave to this UNIQUE constraint; you can read from it which rule was triggered.
When you draw a model, you choose a primary key for each table. Sometimes a natural key is ready: a student's number, a course's code. Even so, you usually prefer a surrogate key (id) that has no meaning and never changes, and put UNIQUE on the natural key. The case does exactly this in the student table: id is the primary key, and student_no is NOT NULL UNIQUE. The reason is that natural keys can change over time: a student's number may have been entered wrongly, and a course's code may change under a new regulation. Because foreign keys point to the surrogate id, correcting the number changes only one row. The hundreds of enrollment rows linked to it are not affected.
An entity can also have a relationship with itself. A course's prerequisite is another course; an employee's manager is another employee; a user was invited to the app by another user. In this case the foreign key points to the primary key of the same table. In the case's course table, prerequisite_id → course.id is such a link, and 9 of the 33 courses have a prerequisite. The conversion rule does not change: "how many prerequisites does a course have? One. How many courses can a course be a prerequisite of? Many." That is 1-N, with the foreign key on the "many" side; here both sides are the same table. To query a relationship like this, you use the self join from lesson 17.
A model is not correct just because you drew it. The best way to check a model is to ask it the questions you expect from the system: "Which clubs is a student a member of?", "How many people attended an event?", "Who is the president of the Chess club?" If you can find a JOIN path for each question, the model is ready for it. If you cannot, a table or a column is missing.
Example 3 (case): The full model of the club system and a check query
CREATE TABLE club ( id INTEGER PRIMARY KEY, name VARCHAR(60) NOT NULL UNIQUE ); CREATE TABLE event ( -- 1-N: club → event id INTEGER PRIMARY KEY, club_id INTEGER NOT NULL REFERENCES club(id), title VARCHAR(100) NOT NULL ); CREATE TABLE club_member ( -- N-M: student ↔ club student_id INTEGER REFERENCES student(id), club_id INTEGER REFERENCES club(id), role VARCHAR(20) NOT NULL DEFAULT 'member', joined_on DATE NOT NULL DEFAULT CURRENT_DATE, PRIMARY KEY (student_id, club_id) ); CREATE TABLE president ( -- 1-1: club → president club_id INTEGER PRIMARY KEY REFERENCES club(id), student_id INTEGER NOT NULL UNIQUE REFERENCES student(id) ); attendance ( student_id INTEGER student(id), event_id INTEGER event(id), (student_id, event_id) ); club (1, ), (2, ); club_member (student_id, club_id) (1, 1), (2, 1), (2, 2); president (1, 2); event (1, 1, ), (2, 1, ), (3, 2, ); attendance (1, 1), (2, 1), (3, 1), (2, 2), (2, 3); s.first_name, s.last_name, c.name club club_member m student s s.id = m.student_id club c c.id = m.club_id s.last_name, c.name;
| first_name | last_name | club |
|---|---|---|
| Anika | Park | Chess |
| Anika | Rivera | Chess |
| Anika | Rivera | Robotics |
Five tables came out of five sentences. Every relationship type in the case is here: club-event is 1-N, student-club and student-event are N-M, and club-president is 1-1. The check query starts from the junction table and joins one table on each side: student 2, Anika Rivera, is in two clubs, and Chess has two students. The same model also answers the question "how many attendees per event?": if you join attendance with event and group by title, Tournament has 3 attendees, Blitz night 1, and Workshop 1.
Put the lines of the check query in order: it lists students with the clubs they belong to, sorted by first name.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Keep one more tip in mind: when you design a model, write the questions you expect from the system in a list. Every new table or column should serve at least one of these questions. A column that serves no question is probably unnecessary, and a question that no path can answer points to a missing piece.
Now make modeling decisions in a scenario. The school library is also moving to the database: a book has several copies, and students borrow copies and bring them back.
The library has tables for books, copies, and students. A book can have several copies; over time a student borrows many copies, and over time many students borrow the same copy. Where do you put the borrowing information (who borrowed which copy, on which day, and returned it on which day)?
Pick an option and see what happens. There are no points; you can try the other options too.
Here the relationship was built between student and copy, not between student and book. The word "book" in the scenario hid two separate entities: the work with a title and an author (book) and the physical object on the shelf (copy). The book-copy relationship is also 1-N: a book has many copies, and a copy has one book. In the practice lesson at the end of the course, you will build this library model from start to finish.
The same rules apply to every database. Read the database of the music app Earbud as a model: artist, song, listener, play, song_like. Look at each table and ask "which relationship is this part of?":
song.artist_id.song_like (listener_id, song_id), with a composite primary key and the relationship attribute liked_on.listener.invited_by_id.Now a new request has come in: listeners should be able to create playlists. A playlist has one owner, and a listener can have many playlists. A playlist contains many songs, a song can appear in many playlists, and the position of the song in the playlist must be stored.
A song can be in many playlists, a playlist has many songs, and every playlist has one owner. How many new tables do playlists need?
Example 4 (outside the case, Earbud): The playlist model
CREATE TABLE playlist ( id INTEGER PRIMARY KEY, listener_id INTEGER NOT NULL REFERENCES listener(id), name VARCHAR(60) NOT NULL, created_on DATE NOT NULL ); CREATE TABLE playlist_song ( playlist_id INTEGER REFERENCES playlist(id), song_id INTEGER REFERENCES song(id), position INTEGER NOT NULL, PRIMARY KEY (playlist_id, song_id) ); INSERT INTO playlist VALUES (1, 1, 'Morning run', '2026-03-01'); INSERT INTO playlist_song VALUES (1, 3, 1), (1, 1, 2), (1, 7, 3); SELECT p.name AS playlist, ps.position, s.title AS song FROM playlist_song ps JOIN playlist p ON p.id = ps.playlist_id JOIN song s ON s.id = ps.song_id ORDER BY ps.position;
| playlist | position | song |
|---|---|---|
| Morning run | 1 | Yellow Bus |
| Morning run | 2 | Platform Three |
| Morning run | 3 | Forty Steps |
playlist_song follows the same pattern as song_like: two foreign keys, a composite primary key, and an attribute of the relationship. position belongs to neither the song nor the playlist; Yellow Bus can be first in this playlist and tenth in another. The check query also starts from the junction table and goes to both sides, just like in the club model.
course.prerequisite_id points to a course in the same table. When you use the table twice with two aliases, each course gets the name of its prerequisite next to it (lesson 17).
SELECT c.code, c.name, p.name AS prerequisite FROM course c JOIN course p ON p.id = c.prerequisite_id ORDER BY c.code LIMIT 4;
Result (first 4 of 9 rows):
| code | name | prerequisite |
|---|---|---|
| BUS203 | Accounting II | Accounting I |
| CPR102 | Algorithms and Programming II | Algorithms and Programming I |
| CPR104 | Databases II | Databases I |
| GEN103 | Quantitative Reasoning II | Quantitative Reasoning I |
The 24 courses without a prerequisite drop out of the INNER JOIN; 9 of the 33 courses remain.
Trying to build a many-to-many relationship with a single foreign key:
OutputCREATE TABLE club (
id INTEGER PRIMARY KEY,
name VARCHAR(60) NOT NULL,
student_id INTEGER REFERENCES student(id)
);If you add student_id to the club table, every club can have only one member; a second member either hits the primary key or splits the club into a second row. If you add club_id to the student table instead, every student can be a member of only one club. If you answer "many" in both directions, you need a junction table (club_member) with two foreign keys and a composite primary key. The second common mistake is the mirror image: in a 1-N relationship, putting the foreign key on the "one" side (club.event_id). The rule is short: the foreign key always goes on the "many" side.
Next lesson: what do we do when we are handed a ready-made, single-table Excel file? With normalization, we will clean out the repeated information and split the table into the right tables.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
You can see that a junction table really carries an N-M relationship by counting, as you did for enrollment in the case.
SELECT COUNT(*) AS likes, COUNT(DISTINCT listener_id) AS listeners, COUNT(DISTINCT song_id) AS songs FROM song_like;
| likes | listeners | songs |
|---|---|---|
| 71 | 20 | 27 |
The 71 likes are spread across 20 listeners and 27 songs. If you group and count, you see that one listener liked at most 11 songs, and one song was liked by at most 8 listeners: "many" in both directions.