A3.2.4
Construct tables for relational databases
A relational table should: represent one entity have a primary key use suitable data types include foreign keys where relationships exist avoid repeating…
-
A relational table should:
- represent one entity
- have a primary key
- use suitable data types
- include foreign keys where relationships exist
- avoid repeating groups
-
When constructing tables:
- Identify the entities
- List the attributes for each entity
- Choose a primary key for each table
- Identify foreign keys to link related tables
- Assign suitable data types
- Add constraints if needed
-
Example tables:
Students
| Field | Data Type | Key |
|---|---|---|
| StudentID | INT | PK |
| Name | VARCHAR(50) | |
| DOB | DATE | |
| VARCHAR(100) |
Classes
| Field | Data Type | Key |
|---|---|---|
| ClassID | INT | PK |
| ClassName | VARCHAR(50) |
Enrollments
| Field | Data Type | Key |
|---|---|---|
| StudentID | INT | PK, FK |
| ClassID | INT | PK, FK |
- Here:
Enrollmentsis a linking table- the composite primary key is
(StudentID, ClassID) - both fields are also foreign keys
- Common constraints to consider:
NOT NULL- field must contain a value
UNIQUE- no duplicate values allowed
PRIMARY KEY- uniquely identifies each record
FOREIGN KEY- links tables and enforces referential integrity