Good schema design prevents bugs that are nearly impossible to fix later. A well-designed schema has no redundancy, enforces invariants at the database level, and makes queries natural to write.
Entity-Relationship (ER) Diagrams#
Before writing SQL, model your domain with an ER diagram. Key elements:
- Entity: a thing with independent existence, such as User, Order, Product
- Attribute: a property of an entity, such as User.name or Order.amount
- Relationship: how entities relate, e.g. User places Orders
A student registers for many courses and a course has many students, so this becomes three tables: students, courses, and a junction table for Registers whose key is (roll_no, course_id). The grade lives there, because it belongs to one student in one course, not to either alone.
Cardinality#
| Relationship | Meaning | Example |
|---|---|---|
| One-to-One (1:1) | Each row maps to at most one in the other table | User ↔ Profile |
| One-to-Many (1:N) | One row in A relates to many rows in B | User → Orders |
| Many-to-Many (M:N) | Many in A relate to many in B | Students ↔ Courses |
Converting ER to Tables#
One-to-Many: put the foreign key on the "many" side.
Many-to-Many: create a junction table (associative entity).
One-to-One: foreign key on either side, with a UNIQUE constraint.
Normalization#
Once your entities are tables, check that every fact is stored exactly once. If the same fact sits in many rows, one update can leave copies that disagree, a new item cannot be added on its own, and deleting one row can lose a fact you needed. Normalization fixes this by splitting tables along their functional dependencies, through 1NF, 2NF, 3NF and BCNF.
The full walk-through, with one college registration table taken through every normal form step by step, is in Normalization in DBMS.
When to Denormalise#
Normalisation removes redundancy but can require many joins for common queries, hurting read performance. Denormalisation deliberately re-introduces redundancy for speed:
Rules for denormalisation:
- Only after measuring that joins are actually slow
- Add write-side code to keep denormalised data in sync
- Document why the redundancy exists
Naming Conventions#
Consistent naming makes a schema self-documenting:
| Convention | Example | |
|---|---|---|
| Tables | Plural, snake_case | user_orders |
| Primary key | id | users.id |
| Foreign key | {table}_id | orders.user_id |
| Timestamps | created_at, updated_at | |
| Boolean | is_ or has_ prefix | is_active, has_verified_email |
What to Remember#
- Model your domain in ER diagrams before writing SQL: entities, attributes, and relationships
- 1:N relationships → foreign key on the "many" side; M:N → junction table
- Normalize so each fact is stored once: see Normalization in DBMS
- Normalise first; denormalise only when you've measured a real performance problem
- Foreign key constraints enforce referential integrity at the DB level, so don't skip them