Table of Contents
- Introduction to Database and Data Model Design
- What Is Data Modeling?
- What Is Database Design?
- Understanding Database Entities
- Attributes and Data Types
- Understanding Entity Relationships
- Types of Database Relationships
- Primary Keys and Foreign Keys
- Database Constraints and Integrity Rules
- Database Normalization
- Relational Database Schema Design
- Practical Example: E-Commerce Database Design
- Database Migrations
- Types of Database Migrations
- Database Migration Best Practices
- Common Database Design Mistakes
- Role of Database Design in Spec-Driven Development
- Conclusion
- Frequently Asked Questions
1. Introduction to Database and Data Model Design
Every software application that stores and processes information depends on an underlying data structure. Whether it is an e-commerce platform, healthcare management system, banking application, or content management system, the way data is organized directly affects application reliability, performance, security, and maintainability.
Database and data model design is the process of identifying the information an application needs, defining how that information is structured, establishing relationships between different data elements, and specifying the rules that protect data integrity.
A well-designed database provides a consistent foundation for application development. It helps prevent duplicate records, incorrect relationships, inconsistent information, and unnecessary complexity.
Four important concepts form the foundation of database design:
- Entities: Represent the important objects or concepts about which the system stores information.
- Relationships: Define how different entities are connected.
- Constraints: Establish rules that protect the accuracy, validity, and consistency of stored data.
- Migrations: Provide a controlled way to introduce changes to the database structure over time.
For example, an e-commerce application may need to store customers, products, orders, payments, and shipments. Database design determines how these entities are represented, how they relate to one another, what information each record must contain, and how the structure evolves when new features are introduced.
In Spec-Driven Development (SDD), database design translates requirements and architectural decisions into a structured data specification. This specification helps developers implement the correct schema and helps AI coding agents understand the expected data structure before generating database-related code.
2. What Is Data Modeling?
Data modeling is the process of identifying, organizing, and describing the data required by a software system.
It defines the entities, attributes, relationships, and business rules that govern how information is represented.
A data model acts as a blueprint for how application information should be structured.
For example, an online shopping application may require the following entities:
- Customer
- Product
- Category
- Order
- Order Item
- Payment
- Shipment
The data model defines the information associated with each entity and the relationships between them.
Objectives of Data Modeling
The main objectives include:
1. Understand Business Information
Identify the important business objects and information the application needs to manage.
2. Organize Data Logically
Define how information should be grouped into entities and attributes.
3. Establish Relationships
Describe how records belonging to different entities are connected.
4. Maintain Data Integrity
Define rules that prevent invalid, incomplete, or inconsistent information.
5. Reduce Data Duplication
Organize information to avoid unnecessary repetition and update anomalies.
6. Support Application Requirements
Ensure that the data model supports business workflows, reporting, integrations, and future changes.
Three Levels of Data Modeling
Data modeling is commonly performed at three levels.
Conceptual Data Model
A conceptual data model provides a high-level view of the major business entities and their relationships.
It focuses on business concepts rather than technical implementation details.
For example, an e-commerce conceptual model may identify Customer, Product, Order, and Payment as the primary entities.
Logical Data Model
A logical data model introduces more detail, including attributes, identifiers, relationships, and cardinality.
It describes the structure of information without being tied to a particular database technology.
For example, a Customer entity may contain Customer ID, Name, Email, and Registration Date.
Physical Data Model
A physical data model describes how the logical model will be implemented in a specific database system.
It includes details such as:
- Table names
- Column names
- Data types
- Primary keys
- Foreign keys
- Indexes
- Constraints
- Database-specific features
For example, a physical model may define a PostgreSQL customers table with a UUID primary key, a unique email column, and timestamp fields.
These three levels help separate business understanding from logical structure and database-specific implementation.
3. What Is Database Design?
Database design is the process of translating a data model into a practical database structure that supports application requirements.
It determines how information is stored, accessed, updated, related, and protected.
Database design involves decisions about:
- Database type and technology
- Tables and columns
- Entities and relationships
- Primary and foreign keys
- Data types and validation
- Constraints and indexes
- Normalization
- Transactions
- Data retention
- Backup and recovery
- Schema evolution
Types of Database Models
Different database technologies organize information in different ways.
Relational Database Model
The relational model stores information in tables consisting of rows and columns. Relationships are established using keys.
Examples include PostgreSQL, MySQL, Microsoft SQL Server, and Oracle Database.
Relational databases are commonly used in applications that require structured data, transactions, and well-defined relationships.
Document Database Model
Document databases store information in flexible document structures, often using JSON-like formats.
Examples include MongoDB and Couchbase.
They are useful when application data has varying structures or when document-oriented access patterns are important.
Key-Value Database Model
Key-value databases store information as key-value pairs.
Examples include Redis and Amazon DynamoDB when used in key-value access patterns.
They are commonly used for caching, session storage, and high-speed lookups.
Graph Database Model
Graph databases represent information using nodes, relationships, and properties.
Examples include Neo4j and Amazon Neptune.
They are useful for applications involving highly connected data, such as recommendation engines, fraud detection, and social networks.
The database model should be selected according to the application’s data structure, access patterns, consistency requirements, scalability needs, and operational constraints.
4. Understanding Database Entities
An entity represents a distinct object, concept, person, event, or resource about which an application needs to store information.
In a relational database, entities are typically represented as tables.
For example, an e-commerce application may contain the following entities:
Customer
Stores information about people who use the application.
Possible attributes:
- Customer ID
- First Name
- Last Name
- Phone Number
- Registration Date
Product
Stores information about items available for purchase.
Possible attributes:
- Product ID
- Product Name
- Description
- Price
- SKU
- Category ID
Order
Stores information about customer purchases.
Possible attributes:
- Order ID
- Customer ID
- Order Date
- Order Status
- Total Amount
Payment
Stores information about payment transactions.
Possible attributes:
- Payment ID
- Order ID
- Payment Reference
- Amount
- Payment Status
- Transaction Date
Identifying Entities
Entities should be identified from business requirements, user workflows, domain concepts, and data-related use cases.
A practical approach includes:
- Identify the important nouns in business requirements.
- Determine which concepts need independent records.
- Identify the information associated with each concept.
- Determine whether a concept has its own lifecycle.
- Identify relationships with other concepts.
- Check whether the entity represents a distinct business object or merely an attribute.
For example, in a requirement stating that customers can place orders containing multiple products, the likely entities include Customer, Order, Product, and Order Item.
The Order Item entity is important because it represents an individual product entry within an order, including its quantity and purchase price.
Entity Naming Conventions
Consistent naming improves database readability and maintainability.
Common practices include:
- Use meaningful and consistent table names.
- Choose singular or plural naming conventions and apply them consistently.
- Avoid unclear abbreviations.
- Use descriptive column names.
- Maintain consistent naming for primary and foreign keys.
- Avoid reserved database keywords as table or column names.
For example, a database may use customers, products, orders, and order_items as table names, with customer_id, product_id, and order_id as identifiers.
5. Attributes and Data Types
An attribute represents a specific property or characteristic of an entity.
In a relational database, attributes are generally implemented as table columns.
For example, a Customer entity may contain:
- customer_id
- first_name
- last_name
- phone_number
- created_at
Each attribute should have an appropriate data type and, where necessary, validation rules.
Common Database Data Types
| Data Type | Purpose | Example |
|---|---|---|
| INTEGER | Whole numbers | Quantity, age |
| BIGINT | Large whole numbers | Large record identifiers |
| DECIMAL | Exact numeric values | Product price |
| VARCHAR | Variable-length text | Name, email |
| TEXT | Longer text | Description |
| BOOLEAN | True or false values | Is active |
| DATE | Calendar date | Date of birth |
| TIMESTAMP | Date and time | Created timestamp |
| UUID | Universally unique identifier | Customer ID |
| JSON / JSONB | Structured document data | Flexible metadata |
The exact types available and their behavior depend on the database technology.
Choosing Appropriate Data Types
Selecting the right data type is important for correctness and storage efficiency.
Use DECIMAL for Financial Values
Financial values should generally use an exact decimal or integer-based representation rather than binary floating-point types.
For example, a product price may use DECIMAL(12,2) where the business requirements support that precision.
Use Appropriate Date and Time Types
Use date types for calendar dates and timestamp types for events that require date and time information.
For applications operating across time zones, define a consistent time-handling strategy. Storing timestamps in UTC is a common approach.
Use Constraints for Required Values
If an attribute must always contain a value, define it as NOT NULL.
Use Appropriate Text Lengths
Choose text types based on the expected content and database capabilities. Avoid arbitrary restrictions that could reject valid business information.
Derived Attributes
Some values can be calculated from other stored attributes.
For example:
- Order total may be calculated from order items, discounts, taxes, and other charges.
- Customer age may be calculated from date of birth.
- Available inventory may be derived from stock and reservation records.
Derived values do not always need to be stored. However, storing calculated values may be justified for performance, auditing, or historical accuracy.
When storing derived values, define how they remain consistent with their source data.
For example, an order should generally preserve the actual purchase price of each item rather than relying on the current product price when displaying an old order.
6. Understanding Entity Relationships
A relationship describes how two or more entities are associated with one another.
Relationships are essential because business information rarely exists in isolation.
For example:
- A customer can place multiple orders.
- An order can contain multiple products.
- A product can belong to multiple categories in some business models.
- An order can have one or more payment attempts.
Database relationships help represent these associations in a structured manner.
Relationship Cardinality
Cardinality defines how many records from one entity can be associated with records from another entity.
Common relationship types include:
One-to-One (1:1)
One record in an entity is associated with at most one record in another entity.
Example:
A user account may have one profile record.
This relationship can be implemented using a foreign key with a unique constraint.
One-to-Many (1:N)
One record in an entity can be associated with multiple records in another entity.
Example:
One customer can place multiple orders, but each order belongs to one customer.
This is commonly implemented by placing a foreign key in the many-side table.
For example, orders.customer_id references customers.customer_id.
Many-to-Many (M:N)
Multiple records in one entity can be associated with multiple records in another entity.
Example:
A product can belong to multiple categories, and a category can contain multiple products.
In a relational database, this relationship is usually implemented through a junction table.
For example:
- products
- categories
- product_categories
The product_categories table stores the associations between products and categories.
Optional and Mandatory Relationships
Relationships may also define whether an association is required.
For example:
- Every order must belong to a customer.
- A customer may have no orders.
- A product may optionally have a category.
- A payment record must belong to an order.
These rules affect foreign key nullability and database constraints.
Entity Relationship Diagrams
An Entity Relationship Diagram (ERD) visually represents entities, attributes, and relationships.
It helps developers understand the data model before implementing database tables.
An ERD typically includes:
- Entity names
- Attributes
- Primary keys
- Foreign keys
- Relationship lines
- Cardinality
- Optionality
Common ERD notations include Crow’s Foot notation and Chen notation.
Crow’s Foot notation is widely used in practical relational database design because it communicates one-to-one, one-to-many, and many-to-many relationships clearly.
7. Types of Database Relationships
Understanding relationships is important when translating business requirements into relational structures.
One-to-One Relationship Example
Consider a user account and its profile.
A simplified structure may include:
Users
- user_id
- password_hash
User Profiles
- profile_id
- user_id
- first_name
- last_name
- date_of_birth
The user_id in User Profiles references the Users table and should have a unique constraint if each user can have only one profile.
One-to-Many Relationship Example
Consider customers and orders.
Customers
- customer_id
- name
Orders
- order_id
- customer_id
- order_date
- status
One customer can have multiple orders. Each order belongs to one customer.
The customer_id foreign key is placed in the Orders table.
Many-to-Many Relationship Example
Consider students and courses.
A student can enroll in multiple courses, and each course can have multiple students.
The relationship can be implemented through an Enrollment table.
Students
- student_id
- student_name
Courses
- course_id
- course_name
Enrollments
- enrollment_id
- student_id
- course_id
- enrollment_date
- enrollment_status
The Enrollment table connects the two entities and can also store attributes specific to the relationship.
This is an important modeling principle: a relationship may itself have information that needs to be stored.
8. Primary Keys and Foreign Keys
Keys are fundamental to relational database design. They identify records and establish relationships between tables.
Primary Key
A primary key uniquely identifies each record in a table.
For example, customer_id may be the primary key of the Customers table.
A primary key must be unique and cannot contain NULL values.
Common primary key strategies include:
- Auto-incrementing integers
- UUIDs
- Application-generated identifiers
- Natural keys, where appropriate
Surrogate keys, such as generated integers or UUIDs, are commonly used because they provide stable identifiers independent of business attributes.
Foreign Key
A foreign key is a column or group of columns that references a candidate key, usually the primary key, in another table.
For example:
orders.customer_id references customers.customer_id.
Foreign keys enforce referential integrity by preventing references to records that do not exist, subject to the configured constraint behavior.
Composite Keys
A composite key consists of two or more columns that together uniquely identify a record.
For example, the combination of student_id and course_id may uniquely identify an enrollment.
A junction table can use this combination as its primary key when the business rules permit only one enrollment record for each student-course pair.
Alternatively, it may use a separate generated primary key and enforce uniqueness through a composite UNIQUE constraint.
Unique Keys
A UNIQUE constraint prevents duplicate values in a column or combination of columns.
For example, an application may require every customer email address to be unique.
The exact treatment of NULL values in unique constraints varies between database systems, so this behavior should be considered when designing schemas.
9. Database Constraints and Integrity Rules
Database constraints are rules enforced by the database to maintain data accuracy and consistency.
They prevent invalid information from being stored, even when data is inserted or modified by different application components.
Application-level validation is important, but database constraints provide an additional layer of protection.
9.1 NOT NULL Constraint
A NOT NULL constraint ensures that a column must contain a value.
Example:
A customer record may require an email address.
CREATE TABLE customers (
customer_id BIGINT PRIMARY KEY,
name VARCHAR(150) NOT NULL,
email VARCHAR(255) NOT NULL
);
9.2 UNIQUE Constraint
A UNIQUE constraint prevents duplicate values.
Example:
CREATE TABLE customers (
customer_id BIGINT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE
);
This ensures that two customer records cannot use the same email address, subject to the database’s unique and NULL semantics.
9.3 PRIMARY KEY Constraint
A PRIMARY KEY constraint uniquely identifies records.
Example:
CREATE TABLE products (
product_id BIGINT PRIMARY KEY,
product_name VARCHAR(200) NOT NULL
);
9.4 FOREIGN KEY Constraint
A FOREIGN KEY constraint ensures that a reference points to an existing record.
Example:
CREATE TABLE orders (
order_id BIGINT PRIMARY KEY,
customer_id BIGINT NOT NULL,
order_date TIMESTAMP NOT NULL,
FOREIGN KEY (customer_id)
REFERENCES customers(customer_id)
);
This prevents an order from referencing a customer who does not exist.
9.5 CHECK Constraint
A CHECK constraint enforces a condition on stored values.
Example:
CREATE TABLE products (
product_id BIGINT PRIMARY KEY,
product_name VARCHAR(200) NOT NULL,
price DECIMAL(12,2) NOT NULL,
CHECK (price >= 0)
);
This prevents negative product prices.
9.6 DEFAULT Constraint
A DEFAULT value is used when an insert operation does not provide a value for a column.
Example:
CREATE TABLE orders (
order_id BIGINT PRIMARY KEY,
status VARCHAR(30) NOT NULL DEFAULT 'PENDING'
);
The default should represent a valid business starting state.
9.7 Referential Integrity Rules
Referential integrity defines how the database handles changes to referenced records.
Common foreign key actions include:
- RESTRICT: Prevents deletion or modification when dependent records exist.
- CASCADE: Automatically applies certain changes to dependent records.
- SET NULL: Sets the referencing foreign key to NULL when the referenced record is deleted or updated, where supported and allowed.
- SET DEFAULT: Sets the referencing column to its default value, where supported.
These actions should be selected according to business rules.
For example, deleting a customer should not automatically delete historical financial transactions or orders unless the business explicitly requires that behavior.
In many business systems, deactivation or soft deletion is more appropriate than physically deleting important records.
Why Database Constraints Matter
Constraints help protect data integrity across the application.
They are particularly important when:
- Multiple services write to the same database.
- Data is imported from external systems.
- Background jobs update records.
- Developers execute manual database operations.
- Applications process concurrent requests.
- Business rules require strict data consistency.
A reliable database design uses constraints to enforce rules that should remain true regardless of which application component performs the operation.
10. Database Normalization
Database normalization is the process of organizing relational data to reduce unnecessary duplication and prevent data anomalies.
It helps create a structure in which information is stored in appropriate tables and relationships are used to connect related records.
Why Normalization Is Important
Poorly designed databases may store the same information in multiple places.
This can lead to:
Update Anomalies: Changing information in one record but not in other records containing the same information.
Insertion Anomalies: Being unable to insert one type of information without also inserting unrelated information.
Deletion Anomalies: Accidentally losing important information when deleting another record.
Normalization reduces these problems by organizing data according to its dependencies.
First Normal Form (1NF)
A table satisfies First Normal Form when its attributes contain values that are atomic for the intended data model and there are no repeating groups represented as multiple values in a single field.
For example, storing multiple product IDs in a single order column is generally unsuitable for a relational order model.
Instead, each order item should be represented as a separate row in an Order Items table.
Second Normal Form (2NF)
A table satisfies Second Normal Form when it is in 1NF and every non-key attribute depends on the whole candidate key, rather than only part of a composite candidate key.
This is particularly relevant to tables with composite keys.
For example, consider an Enrollment table with a composite key consisting of Student ID and Course ID.
If Course Name depends only on Course ID, storing it in the Enrollment table creates a partial dependency.
Course Name should generally be stored in the Courses table instead.
Third Normal Form (3NF)
A table satisfies Third Normal Form when it is in 2NF and non-key attributes do not have inappropriate transitive dependencies on candidate keys.
For example, consider a table containing:
- Employee ID
- Department ID
- Department Name
If Department Name depends on Department ID rather than directly on Employee ID, it may be better represented in a separate Departments table.
The Employee table can reference the Department through Department ID.
Denormalization
Denormalization intentionally introduces some redundancy to improve read performance or simplify specific access patterns.
For example, an analytics system may maintain precomputed summaries rather than repeatedly joining large transactional tables.
Denormalization should be based on measured performance needs and should include a strategy for maintaining consistency.
Normalization and denormalization are design choices, not competing rules. A well-designed system balances data integrity, query requirements, performance, and maintainability.
11. Relational Database Schema Design
A database schema defines the logical structure of a database, including tables, columns, data types, relationships, constraints, and other database objects.
Schema design translates the logical data model into a structure that can be implemented in a relational database.
Important Considerations in Schema Design
Table Structure
Each table should represent a clearly defined entity or relationship.
Column Design
Columns should have meaningful names, appropriate types, and well-defined nullability.
Key Strategy
Choose primary keys and foreign keys that support reliable identification and relationships.
Indexing
Indexes should support important query patterns and frequently used filters, joins, and sorting operations.
However, excessive indexing can increase storage requirements and slow down write operations.
Transactions
Define which operations need to be performed atomically to maintain business consistency.
Data Lifecycle
Consider how records are created, updated, archived, retained, and deleted.
Security
Identify sensitive information and define access controls, encryption requirements, and data protection rules.
Auditability
Determine whether important changes need to be recorded for operational, financial, regulatory, or troubleshooting purposes.
Example: Relational Schema for an E-Commerce Application
A simplified e-commerce schema may contain:
Customers
- customer_id (Primary Key)
- name
- created_at
Products
- product_id (Primary Key)
- product_name
- description
- price
- sku
- category_id
Categories
- category_id (Primary Key)
- category_name
Orders
- order_id (Primary Key)
- customer_id (Foreign Key)
- order_date
- order_status
- total_amount
Order Items
- order_item_id (Primary Key)
- order_id (Foreign Key)
- product_id (Foreign Key)
- quantity
- unit_price
Payments
- payment_id (Primary Key)
- order_id (Foreign Key)
- payment_reference
- amount
- payment_status
This structure separates customer, product, order, and payment information while maintaining relationships through keys.
The Order Items table represents the many-to-many association between Orders and Products.
It also stores purchase-specific information such as quantity and unit price. This is important because the current product price may change after an order has been placed.
A production database may require additional entities for addresses, shipping, refunds, discounts, inventory reservations, tax calculations, and payment attempts.
12. Practical Example: E-Commerce Database Design
Consider an e-commerce platform that allows customers to browse products, add products to a cart, place orders, and make payments.
The database design should support the complete lifecycle of a purchase.
Step 1: Identify Business Entities
The primary entities include:
- Customer
- Address
- Product
- Category
- Cart
- Cart Item
- Order
- Order Item
- Payment
- Shipment
Step 2: Define Attributes
Each entity receives attributes based on its business responsibilities.
For example:
Customer
- customer_id
- name
- password_hash
- created_at
Order
- order_id
- customer_id
- billing_address_id
- shipping_address_id
- order_status
- order_date
- total_amount
Order Item
- order_item_id
- order_id
- product_id
- quantity
- unit_price
- line_total
Step 3: Define Relationships
The important relationships include:
- One customer can have multiple addresses.
- One customer can place multiple orders.
- One order can contain multiple order items.
- One product can appear in multiple order items.
- One order may have multiple payment attempts.
- One order may have one or more shipments, depending on the fulfillment model.
Step 4: Define Constraints
The database should enforce important rules.
Examples:
- Customer email must be unique if the business requires one account per email.
- Order must reference an existing customer.
- Order item quantity must be greater than zero.
- Product price must not be negative.
- Payment amount must satisfy the applicable transaction rules.
- Order item must reference an existing order.
- Required order and payment statuses must use valid values.
Some business rules require more than a simple column constraint. For example, ensuring that an order total matches all its items, taxes, and discounts may require transactional application logic or database-level mechanisms appropriate to the system.
Step 5: Define Data Ownership
Each entity should have a clear ownership model.
For example:
- Customer Management owns customer records.
- Product Catalog owns product information.
- Order Management owns orders and order items.
- Payment Management owns payment transaction records.
- Shipping Management owns shipment information.
In a modular monolith, these may be logical ownership boundaries within one application and database.
In a microservices architecture, they may become separate service-owned data stores. The design should avoid allowing unrelated services to modify another service’s data directly without an explicit contract.
Step 6: Define Lifecycle and Retention
The design should also specify what happens when records are no longer active.
For example:
- Customers may be deactivated.
- Products may be discontinued.
- Orders may be archived according to retention policies.
- Payment records may need to be retained for audit purposes.
- Personal information may require deletion, anonymization, or restricted retention depending on applicable obligations.
The database design should support these lifecycle requirements from the beginning.
13. Database Migrations
A database migration is a controlled change to the database schema or, in some cases, its data.
Software applications evolve continuously. New features may require additional tables, columns, indexes, relationships, or constraints.
For example, an existing application may initially store customer names and email addresses. A new feature may require customer preferences, additional contact information, or account verification status.
Database migrations provide a structured way to introduce these changes across development, testing, staging, and production environments.
Why Database Migrations Matter
Database migrations help teams:
- Evolve database schemas in a controlled manner.
- Apply consistent changes across environments.
- Track the history of database modifications.
- Support coordinated application releases.
- Reduce manual database configuration errors.
- Review and audit schema changes.
- Recover from certain failed deployment scenarios.
- Keep database structures aligned with application code.
Without a migration strategy, different environments may gradually develop inconsistent database structures.
What Does a Database Migration Contain?
A migration typically includes:
Migration Identifier
A unique version, timestamp, or sequence number identifying the migration.
Description
A short explanation of the change.
Schema Changes
Instructions to create, modify, or remove database objects.
Data Changes
Optional operations to transform or populate existing records.
Execution Order
The migration system determines which changes must be applied and in what order.
Rollback Strategy
Where supported and appropriate, a migration may include a corresponding rollback operation.
Not every migration can be safely reversed. For example, dropping a column permanently removes information unless it has been preserved elsewhere.
14. Types of Database Migrations
Database migrations can be categorized according to the type of change they introduce.
14.1 Schema Migrations
Schema migrations modify the database structure.
Examples include:
- Creating a new table.
- Adding a column.
- Modifying a column type.
- Adding a foreign key.
- Creating an index.
- Adding a unique constraint.
- Renaming a table.
- Removing an obsolete column.
Example: Adding a phone number column to the Customers table.
ALTER TABLE customers
ADD COLUMN phone_number VARCHAR(20);
This migration introduces a new attribute without requiring existing records to contain a phone number immediately.
14.2 Data Migrations
Data migrations modify existing records to match a new data structure or business requirement.
For example, an application may previously store a customer’s full name in one column but later introduce separate first-name and last-name columns.
A data migration may:
- Add the new columns.
- Read existing full-name values.
- Transform the values according to defined rules.
- Populate the new columns.
- Validate the migrated information.
- Remove the old column after the application no longer depends on it.
Data transformations should account for incomplete, inconsistent, and unexpected historical records.
14.3 Versioned Migrations
Versioned migrations use a sequence of migration files or identifiers.
For example:
- V001: Create customers table.
- V002: Create products table.
- V003: Create orders table.
- V004: Add payment status.
- V005: Create order indexes.
The migration system tracks which changes have already been applied.
This approach is commonly used in collaborative software development because it provides a consistent, reviewable history of database changes.
14.4 Forward-Only Migrations
Some teams use forward-only migration strategies in which production schema changes are not reversed through automatic rollback scripts.
Instead, a new migration is created to correct or compensate for an earlier change.
This approach can be safer for complex production systems, especially when a migration has already modified or removed data.
14.5 Expand-and-Contract Migrations
Expand-and-contract is a migration strategy used to introduce database changes without requiring all application instances to change simultaneously.
It is particularly useful in applications with continuous deployment, multiple running application versions, and microservices.
A typical process includes:
Expand
Introduce the new schema while keeping the old structure available.
Migrate
Update application code to support the new structure and gradually move data or usage to it.
Contract
Remove the old structure only after all relevant application components no longer depend on it.
For example, when renaming a database column, the team may first add the new column, update the application to support both columns, migrate existing values, and remove the old column in a later release.
This avoids breaking older application instances during deployment.
15. Database Migration Best Practices
Database migrations require careful planning because mistakes can affect application availability and data integrity.
The following practices help reduce migration risks.
Use Version-Controlled Migration Files
Store migration files alongside application code or in a dedicated version-controlled repository.
This ensures that database changes are reviewed and tracked.
Test Migrations Before Production
Apply migrations in development and staging environments before deploying them to production.
Test both schema changes and data transformations.
Avoid Destructive Changes Without Preparation
Dropping columns, tables, or constraints can cause permanent data loss or break older application versions.
Confirm that the data is no longer required and that dependent application code has been updated.
Make Changes Backward-Compatible Where Possible
During rolling deployments, older and newer application versions may run simultaneously.
Schema changes should account for this transition.
Expand-and-contract migrations are useful for managing such changes.
Consider Migration Locking and Concurrency
Migration tools should prevent multiple deployment processes from applying the same migration simultaneously.
The team should understand how the selected database and migration tool handle locking and transaction behavior.
Manage Large Data Migrations Carefully
Updating millions of records in a single operation can create long-running transactions, excessive locking, replication delays, or resource pressure.
Large migrations may require batching, background processing, progress tracking, and resumable execution.
Define Rollback and Recovery Strategies
Understand whether the migration can be reversed safely.
For destructive changes, consider backups, snapshots, data preservation, and forward-fix strategies.
A rollback script is not a substitute for a reliable recovery plan.
Monitor Production Migrations
Monitor execution time, database load, errors, locks, and application behavior after deployment.
Confirm that the application continues to operate correctly after the schema changes.
Maintain Migration Consistency Across Environments
Development, testing, staging, and production environments should follow the same migration history.
Avoid undocumented manual schema changes that cause environment drift.
16. Database Design Tools and Technologies
Several tools and technologies support data modeling, database design, schema management, and migrations.
Data Modeling and Diagramming Tools
Common tools include:
- MySQL Workbench
- DBeaver
- pgModeler
- ER/Studio
- Lucidchart
- diagrams.net
These tools help visualize entities, relationships, keys, and database structures.
Relational Database Systems
Common relational database systems include:
- PostgreSQL
- MySQL
- Microsoft SQL Server
- Oracle Database
- SQLite
Each has its own capabilities, data types, constraint behavior, indexing options, and migration considerations.
Database Migration Tools
Popular migration tools include:
Flyway
Supports versioned database migrations and schema change management.
Liquibase
Provides structured database change management through migration definitions.
Prisma Migrate
Supports schema migration workflows for applications using Prisma ORM.
TypeORM Migrations
Provides migration support for applications using TypeORM.
Sequelize Migrations
Supports database schema changes in Sequelize-based applications.
Knex Migrations
Provides migration capabilities for JavaScript and TypeScript applications using Knex.
The choice of tool should depend on the database technology, application framework, deployment process, and team’s migration strategy.
17. Common Database Design Mistakes
Poor database design can create problems that become increasingly expensive to fix as an application grows.
Common mistakes include:
1. Missing Primary Keys
Every table representing independently identifiable records should have an appropriate key strategy.
2. Incorrect Relationships
Incorrect cardinality or missing foreign keys can lead to inconsistent records.
3. Unnecessary Data Duplication
Storing the same information repeatedly can create update and deletion anomalies.
4. Incorrect Data Types
Using unsuitable types can cause precision problems, invalid values, and unnecessary storage overhead.
5. Overusing Nullable Columns
Allowing NULL values without a clear reason can make business rules and application queries more complicated.
6. Missing Constraints
Relying entirely on application validation can allow invalid data to enter through other write paths.
7. Excessive Normalization
Creating too many small tables without considering actual query patterns can make application queries unnecessarily complex.
8. Premature Denormalization
Duplicating data before understanding performance requirements can introduce unnecessary consistency problems.
9. Missing Indexes
Important queries may become slow when suitable indexes are absent.
10. Excessive Indexing
Too many indexes increase storage usage and can slow down inserts, updates, and deletes.
11. Unsafe Database Migrations
Removing columns or changing data types without considering existing application versions can cause deployment failures.
12. Ignoring Data Lifecycle Requirements
Failure to plan retention, archiving, deletion, and anonymization can create long-term operational and compliance problems.
13. Unclear Data Ownership
When multiple components can independently modify the same business data, consistency and debugging become more difficult.
18. Role of Database Design in Spec-Driven Development
Database and data model design is an important stage in Spec-Driven Development because it defines how business information will be represented and managed by the application.
A specification should not stop at describing application features. It should also explain the data structures and integrity rules required to support those features.
For example, a requirement stating that customers can place orders containing multiple products should lead to a data design that identifies:
- Customer entity
- Order entity
- Product entity
- Order Item entity
- Customer-to-Order relationship
- Order-to-Order Item relationship
- Order Item-to-Product relationship
- Required keys and constraints
- Order and payment lifecycle information
These details help developers implement the correct database structure rather than making assumptions during coding.
Database Specifications as Part of SDD
A database specification may include the following:
1. Entity Definitions
List all entities and explain their business purpose.
2. Attribute Definitions
Document column names, data types, required values, defaults, and validation rules.
3. Relationship Definitions
Specify relationship cardinality, optionality, primary keys, and foreign keys.
4. Integrity Constraints
Document uniqueness, check constraints, referential integrity, and other business rules.
5. Indexing Requirements
Identify important query patterns and the indexes needed to support them.
6. Data Lifecycle
Define creation, modification, retention, archival, and deletion behavior.
7. Migration Requirements
Document how the schema will evolve and how existing data will be handled.
8. Security Requirements
Identify sensitive fields, access boundaries, encryption needs, and audit requirements.
How AI Coding Agents Use Database Specifications
AI coding agents can use database specifications to generate:
- Database schema definitions
- ORM models
- Entity classes
- SQL migration files
- Repository methods
- Validation logic
- Database-related tests
- Seed data
For example, an agent implementing an order management feature can use an approved data model to understand that an Order contains multiple Order Items and that each Order Item references a Product.
Without this context, an agent might incorrectly store product information directly in the Order table or create an unsuitable relationship.
Validating AI-Generated Database Changes
AI-generated database code should be reviewed before it is applied to important environments.
Review should include:
- Correctness of table and column definitions.
- Accuracy of primary and foreign keys.
- Relationship cardinality.
- Constraint definitions.
- Data type selection.
- Indexing decisions.
- Migration safety.
- Backward compatibility.
- Data integrity.
- Performance implications.
Generated migration files should be tested against realistic data and representative application workflows.
Human review remains essential because a syntactically valid schema does not necessarily represent the correct business model.
Keeping Specifications and Database Schemas Aligned
As an application evolves, the data model and physical database schema may change.
These changes should be reflected in the relevant specifications.
For example, introducing multiple payment attempts may require:
- A revised payment entity.
- A new relationship between orders and payment attempts.
- Updated payment status rules.
- New constraints and indexes.
- A database migration.
- Updated application workflows and tests.
Maintaining alignment between requirements, data models, migration files, and implementation helps prevent specification drift.
19. Conclusion
Database and data model design provide the foundation for storing, organizing, and managing application information.
Entities define the important objects in a system. Attributes describe their properties. Relationships connect different entities, while primary keys and foreign keys establish reliable record identification and associations.
Database constraints protect data integrity by enforcing rules such as uniqueness, required values, valid ranges, and referential consistency. Normalization helps organize information and reduce unnecessary duplication.
As applications evolve, database migrations provide a controlled mechanism for changing schemas and transforming existing data without losing consistency.
In Spec-Driven Development, database design turns business and technical requirements into a precise data specification. It gives developers and AI coding agents a clear understanding of the expected entities, relationships, constraints, and migration strategy.
A well-designed database is not simply a collection of tables. It is a structured representation of the application’s business domain, designed to support correctness, maintainability, performance, and future growth.
20. Frequently Asked Questions
1. What is database and data model design?
Database and data model design is the process of identifying application data, organizing it into entities and attributes, defining relationships, establishing constraints, and implementing the structure in a database.
2. What is an entity in database design?
An entity is a distinct object or concept about which a system stores information. In relational databases, entities are generally represented as tables. Examples include Customer, Product, Order, and Employee.
3. What is an entity relationship diagram?
An Entity Relationship Diagram (ERD) is a visual representation of entities, attributes, keys, and relationships in a data model. It helps developers understand the database structure before implementation.
4. What are the three main types of database relationships?
The three common relationship types are one-to-one, one-to-many, and many-to-many. They describe how records in one entity can be associated with records in another entity.
5. What is the difference between a primary key and a foreign key?
A primary key uniquely identifies a record in a table. A foreign key references a key in another table and helps establish relationships and enforce referential integrity.
6. What are database constraints?
Database constraints are rules enforced by the database to maintain data integrity. Common constraints include NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT.
7. What is database normalization?
Database normalization is the process of organizing relational data to reduce unnecessary duplication and prevent insertion, update, and deletion anomalies. Common normal forms include 1NF, 2NF, and 3NF.
8. What is the difference between a conceptual, logical, and physical data model?
A conceptual model describes high-level business entities and relationships. A logical model adds attributes, keys, and relationship details. A physical model defines the actual database implementation, including tables, columns, data types, indexes, and constraints.
9. What is a database schema?
A database schema defines the structure of a database, including tables, columns, data types, relationships, constraints, indexes, and other database objects.
10. What is a database migration?
A database migration is a controlled change to a database schema or its existing data. Migrations are used to introduce new tables, modify columns, add constraints, transform records, and remove obsolete structures.
11. What is the difference between a schema migration and a data migration?
A schema migration changes the database structure, such as adding a column or creating a table. A data migration changes existing records, such as transforming values or moving information into a new structure.
12. What is an expand-and-contract database migration?
Expand-and-contract is a migration strategy that introduces a new database structure while keeping the old structure temporarily available. Application code is gradually updated, data is migrated, and the old structure is removed only after it is no longer needed.
13. Which tools are commonly used for database migrations?
Common database migration tools include Flyway, Liquibase, Prisma Migrate, TypeORM Migrations, Sequelize Migrations, and Knex Migrations. The appropriate choice depends on the application stack and database technology.
14. Why is database design important in Spec-Driven Development?
Database design translates business requirements into a structured data model. It gives developers and AI coding agents clear definitions of entities, relationships, constraints, and migrations, reducing assumptions and helping maintain consistency between specifications and implementation.







