- This topic is empty.
-
AuthorPosts
-
May 30, 2026 at 1:34 pm #6710
Source: https://cs50.harvard.edu/sql/psets/2/donuts/
Question
While working on the CS50 SQL Donuts problem set, I identified the following tables:
- ingredients
- donuts
- customers
- orders
- donut_ingredients (many-to-many relationship between donuts and ingredients)
Is it true that 5 tables are needed?
Answer
Yes, a 5-table design is a reasonable normalized database schema.
The first four tables store the main entities:
- ingredients
- donuts
- customers
- orders
However, there is a many-to-many relationship between donuts and ingredients:
- One donut can contain many ingredients.
- One ingredient can be used in many donuts.
Relational databases cannot directly store many-to-many relationships, so a junction table is needed.
Example
Instead of:
donuts ------ id | name | ingredientswe create:
ingredients ----------- id | namedonuts ------ id | namedonut_ingredients ----------------- donut_id | ingredient_idThis allows each donut to be linked to multiple ingredients and each ingredient to be linked to multiple donuts.
Is 5 Tables Always Enough?
Not necessarily.
There is another many-to-many relationship:
- One order can contain many donuts.
- One donut can appear in many orders.
A fully normalized design often introduces a sixth table:
order_items ----------- order_id | donut_idThe complete schema becomes:
customers | v orders orders <----> order_items <----> donuts donuts <----> donut_ingredients <----> ingredientsKey Takeaway
A 5-table design is sufficient to model the donut–ingredient relationship.
However, if you want a fully normalized database that also properly models orders containing multiple donuts, a 6-table design using an additional
order_itemsjunction table is usually preferred. -
AuthorPosts
- You must be logged in to reply to this topic.
