Course outline · 0% complete

0/29 lessons0%

Course overview →

One-to-Many and Many-to-Many

lesson 8-2 · ~12 min · 23/29

The two shapes of relationships

Almost every schema is built from two relationship shapes:

One-to-many. One customer has many orders, one order belongs to one customer. You already built this in lesson 5-1: put a foreign key on the many side (orders.customer_id).

Many-to-many. One post can have many tags, and one tag can label many posts. Neither side can hold a single foreign key, because each side needs several pointers. The fix is a third table, a junction table (also called a join table), where each row records one connection:

CREATE TABLE post_tags (
  post_id INTEGER,
  tag_id INTEGER
);

You met one already without the name: enrollments in lesson 6-2 connected students to courses many-to-many, and carried extra data about the connection (the grade).

one-to-manycustomer 1order 101order 103foreign key lives on themany side (customer_id)many-to-many (junction table)SQL tipsCoffee guidepost_tags1 · tech1 · beginner2 · food2 · beginnertechfoodbeginner
Top: one-to-many needs only a foreign key on the many side. Bottom: many-to-many needs a junction table where each row is one post-tag connection.

Code exercise · sql

Run it. The double join walks post_tags outward to both real tables, turning id pairs into readable title-tag lines.

Quiz

Your app has playlists and songs. A playlist holds many songs, and the same song can appear in many playlists. What does the schema need?

Code exercise · sql

Your turn. Which tags label 2 or more posts? Print the tag name and its post count. This is the GROUP BY + HAVING pattern from lesson 4-3, applied to a junction table. Only 'beginner' qualifies.