Designing Before Building
Before you create a single table, you need to design your database. ER diagrams (Entity-Relationship diagrams) are the standard way to visualize and plan database schemas. They help you identify entities, their attributes, and how they relate to each other.
Entities and Attributes
- Entity β A thing or concept you want to store data about. Represented as a rectangle. Examples: Student, Course, Order.
- Attribute β A property of an entity. Represented as an oval. Examples: Name, Email, Price.
- Key Attribute β An attribute that uniquely identifies an entity. Underlined in the diagram.
ER Diagram Notation
Chen Notation (classic):
ββββββββββββ ββββββββββββ
β Student β β Course β
ββββββ¬ββββββ ββββββ¬ββββββ
β β
ββββββ΄βββββ ββββββ΄βββββ
β StudentIDβ β CourseIDβ
β Name β β Title β
β Email β β Credits β
βββββββββββ βββββββββββ
Relationship: β Enrolls β
βββ M βββββ 1 βββββ
Student Enrolls Course
(Many) (Many)
Cardinality
Cardinality defines how many instances of one entity can relate to instances of another:
One-to-One (1:1): One-to-Many (1:N): Many-to-Many (M:N):
βββββ βββββ βββββ βββββ βββββ βββββ
β A βββββ B β β A βββββ B β β A βββββ B β
βββββ βββββ βββββ 1β βββββ βββββ Mβ βββββ
1:1 1β N Mβ N
(deptsβemps) (studentsβcourses)
Example ER Diagram: University
ββββββββββ ββββββββββββββ ββββββββββ
βStudent βββββ M βββ€ Enrolls βββ N βββββCourse β
β--------β ββββββββββββββ β--------β
βStdID(PK)β ββββββββββββββ βCrsID(PK)β
βName βββββ 1 βββ€ Belongs To βββ N βββββTitle β
βEmail β ββββββββββββββ βCredits β
ββββββββββ ββββββββββ
β β
β N β 1
βΌ βΌ
ββββββββββββββ ββββββββββββββ
β Department β β Instructor β
β------------β β------------β
βDeptID (PK) β βInsID (PK) β
βDeptName β βName β
ββββββββββββββ βDeptID (FK) β
ββββββββββββββ
From ER Diagram to Tables
Once you have your ER diagram, converting it to tables is straightforward:
- Each entity becomes a table.
- Each attribute becomes a column.
- 1:N relationships: put the primary key of the "1" side as a foreign key in the "N" side.
- M:N relationships: create a junction table with foreign keys from both sides.