Database Migration — Explained with Examples
A database migration is a version-controlled change to a database schema, allowing teams to evolve the database incrementally alongside application code.
Database Migration (also called schema migration or evolution) is a technique for managing incremental, reversible changes to a database schema. Tools like Flyway (Java), Alembic (Python), EF Migrations (.NET), and Prisma Migrate (TypeScript) automate this process.
Why Migration Matters
Without migrations, schema changes are applied manually — leading to drift between environments, missing columns in production, and no audit trail. Migrations version-control the schema alongside application code, so every environment stays in sync and changes are reproducible.
Real-World Analogy
Renovating a house while living in it. You don’t demolish the entire house and rebuild (drop and recreate the database). Instead, you change one room at a time (add a column, rename a table), document each change, and ensure the house remains livable during construction.
Example: Alembic Migration
"""Migration: add user roles table
Revision ID: 0002
Create Date: 2026-06-15
"""
from alembic import op
import sqlalchemy as sa
# Upgrade — apply the change
def upgrade():
op.create_table(
'roles',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('name', sa.String(50), nullable=False),
sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id')),
)
# Downgrade — revert the change
def downgrade():
op.drop_table('roles')
# Usage:
# alembic upgrade head → applies all pending migrations
# alembic downgrade -1 → reverts the last migrationRelated Terms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro