Stop 10 · Schema Design & ConstraintsTopics · 8/11

One-to-Many and Many-to-Many Relationships

Part of the SQL Roadmap

In short

Almost every design question comes down to "how many of these go with how many of those?". Get the answer right and the tables almost design themselves.

One-to-many uses a foreign key on the 'many' side. Many-to-many, like students and courses, needs a junction table holding both keys.

The jaadu sits among towering stacks of books in a crowded old bookshop, tying coloured strings between author portraits and several books at once.

Think of it like this

Books on College Street

In a College Street bookshop in Kolkata, every book has one publisher, but a publisher prints many books: one-to-many. A book can also have several authors, and an author writes several books: many-to-many. For that, the shop keeps a separate credits register that pairs each author with each book.

Watch it happen

Two relationship shapes

One-to-many

  • publishers 1 → many books
  • Put publisher_id on books
  • Two tables are enough

Many-to-many

  • authors many ↔ many books
  • Add a junction table book_authors
  • It holds author_id and book_id

The foreign key always goes on the 'many' side. When both sides are 'many', create a table in the middle.

The big ideas

What you need to know

FK on the many side

Each book has one publisher, so books gets publisher_id. Never store a list of book IDs on publishers.

Junction tables

book_authors has one row per author and book pair. Three authors on one book means three rows.

Composite primary key

PRIMARY KEY (book_id, author_id) stops the same pair being added twice.

Pairs can carry data

The junction can hold extra columns about the pairing, like author_order or role (author, translator).

See it in code

Walk through the code

sql
1CREATE TABLE books (2  book_id      INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,3  title        VARCHAR(200) NOT NULL,4  publisher_id INTEGER NOT NULL REFERENCES publishers (publisher_id)5);6 7CREATE TABLE book_authors (8  book_id      INTEGER REFERENCES books (book_id) ON DELETE CASCADE,9  author_id    INTEGER REFERENCES authors (author_id),10  author_order SMALLINT NOT NULL DEFAULT 1,11  PRIMARY KEY (book_id, author_id)12);13 14SELECT b.title, a.author_name15FROM books b16JOIN book_authors ba ON ba.book_id = b.book_id17JOIN authors a       ON a.author_id = ba.author_id18ORDER BY b.title, ba.author_order;

1/4One-to-many: each book stores its single publisher's ID.

A one-to-many link and a many-to-many junction, then a query across them. Assumes publishers and authors tables exist. Works in PostgreSQL. In MySQL and SQL Server, swap the identity syntax for AUTO_INCREMENT or IDENTITY(1,1).

Save yourself the pain

Common mistakes

Oops

Storing authors as a comma-separated string like 'Ruskin Bond, Anita Desai' in books.

Do this instead

You can't join, index or count that properly. Use a book_authors junction table.

Oops

Adding author1_id, author2_id, author3_id columns.

Do this instead

A book with a fourth author breaks the design. A junction table handles any number of authors.

Your mission

Model a food delivery app

~25 min

Quick check

Students take many courses and courses have many students. How do you model it?

Go deeper

  1. 1Design a junction table for students and courses with an enrolment date.
  2. 2Write a query listing each student's courses through the junction table.
  3. 3Decide what the primary key of the junction table should be.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge