One-to-Many and Many-to-Many, Drawn Out
Tables become powerful when they are linked. There are three common shapes of link, and each is easiest to understand as a drawing. Below, each diagram is described with a caption and numbered steps, so you can sketch it as you read.
Diagram 1: one-to-many
Picture: a box labelled authors on the left and books on the right. A single line leaves authors and splits into three prongs (a "crow's foot") as it reaches books.
Caption: one author can write many books; each book has one author.
- Each author row has a primary key,
id. - Each book row has a column
author_id. author_idholds theidof the author who wrote it. This is a foreign key.- The crow's foot sits on the "many" side,
books.
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author_id INTEGER REFERENCES authors(id)
);
Diagram 2: many-to-many
Picture: students on the left, courses on the right, and a smaller box in the middle called enrolments. A crow's foot points into enrolments from each side.
Caption: a student takes many courses; a course has many students. You cannot store that with one foreign key, so a linking table sits in the middle.
enrolmentshas two columns:student_idandcourse_id.- Each row says "this student is in this course".
- The pair
(student_id, course_id)is usually unique, so a student cannot enrol twice in the same course. - To list a student's courses, you join
studentstoenrolmentstocourses.
| student_id | course_id |
|---|---|
| 1 | 101 |
| 1 | 102 |
| 2 | 101 |
Diagram 3: one-to-one
Picture: users and user_profiles joined by a single straight line with no crow's foot.
Caption: each user has at most one profile, and each profile belongs to exactly one user.
user_profiles.user_idrefers tousers.id.- A UNIQUE rule on
user_profiles.user_idstops a second profile for the same user. - One-to-one tables are less common; often the columns could live in the same table. They are useful for optional or rarely used details.
How to tell which shape you need
| Ask | If the answer is... | Shape |
|---|---|---|
| Can one A have many B? Can one B have many A? | Yes and no | One-to-many |
| Yes and yes | Many-to-many with a linking table | |
| No and no | One-to-one |
Reading the crow's foot
The crow's foot always sits on the "many" side. Some diagram tools add small circles or bars meaning "zero allowed" or "at least one". You do not need those details at first; knowing which end is "many" is enough to design your tables.
Try it
Pick two things from your own project, such as recipes and ingredients. Ask the two questions in the table, decide the shape, and draw it. Then write the CREATE TABLE statements. Our guide on adding a foreign key between two tables helps with the SQL.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.