Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases Querying Relational Databases Table Relationships Many to Many Relationships

Adam Sawicki
Adam Sawicki
15,967 Points

Many to Many Relationship

Hi,

Why can't we create composite primary key in each table of many to many relationship, instead of creating extra table which keeps only composite PKs?

BR, Adam

1 Answer

Kevin Korte
Kevin Korte
28,148 Points

Because you'd inevitably end up with a bunch of null cells in your table. Because of the nature of a many to many, one row in your table may have a relation with 3 others, while the next row might have a relationship with 7 others. You would need to store the primary keys for each relationship. So your table would have to be as big as the row with the most amount of "others" and you wouldn't easily be able to have more than that many relationships, without expanding your database even larger.

Ultimately, it's not as flexible as a schema, and it's not a sustainable model either.

By moving our many to many relationship to a 3rd table, a couple things happen. One, we avoid null rows since we know that each row in that table is just going to be keys to other rows, and two, we no longer have a limit on how many relationships "many" actually is. If we have a row that had 200 hundred other relationships, it wouldn't matter, we'd just have 200 new entries in our many to many table. It's fully sustainable this way.

Hope that makes sense.

Kevin Gates
Kevin Gates
15,052 Points

Best Answer should be awarded to the above.