Introduction
The biggest mistake database developers make is opening their code editor too soon. Before you write a single line of Laravel migration code, before you even think about MySQL or PostgreSQL, you need to think—and more importantly, you need to draw.
In this lesson, you’ll learn why database design starts with pen and paper (or whiteboard and marker), and how to translate real-world problems into database structures that actually work.
Why Design Before Code?
Changing a database is expensive. Once you have data, changing table structures means migrations, data transformations, and potential downtime. A bad database design can haunt a project for years.
Code is easy to change. Data structures are not.
Consider this: If you realize your PHP function needs to return a different value, you change the function. Done. But if you realize your users table needs to track multiple addresses instead of one, you’re looking at:
- New tables
- Data migration
- Updating all existing queries
- Modifying application logic
- Testing everything again
Lesson learned: Invest 2 hours in design to save 20 hours in refactoring.
The Four Foundation Questions
Before designing any database, answer these four questions:
1. What things do I need to store?
These become your tables (also called entities).
Example: In a blog application, you need to store:
- Authors
- Posts
- Categories
- Comments
2. What do I need to know about each thing?
These become your columns (also called attributes or fields).
Example: For a Post, you need:
- Title
- Content
- Publication date
- Author (who wrote it)
- Category
3. How do these things relate to each other?
These become your foreign keys and relationships.
Example:
- An Author writes many Posts
- A Post belongs to one Category
- A Post has many Comments
4. What will I need to find or report on later?
These inform your indexes and query optimization.
Example:
- “Show me all posts by this author”
- “Find all comments from the last week”
- “List posts in a specific category”
The Noun Test: Finding Your Entities
Here’s a simple technique to identify what tables you need:
Step 1: Write down your application requirements in plain English.
Step 2: Underline all the nouns.
Step 3: Nouns typically become tables.
Example
“We’re building a course platform where instructors create courses that contain multiple lessons. Students can enroll in courses and track their progress. Each lesson can have comments from students.”
Potential tables identified:
- courses
- instructors
- lessons
- students
- enrollments (the relationship between students and courses)
- progress
- comments
Pro tip: Not every noun becomes a table. “Each lesson can have a title” – “title” is an attribute of lessons, not a separate table.
In next Chapter we will learn Relationships.
