Why Use Migrations?
Migrations offer several benefits:- Version Control: Track all database changes in your repository
- Repeatability: Apply the same changes consistently across environments
- Rollback: Revert changes if something goes wrong
- Collaboration: Share schema changes with your team
- Documentation: Migrations serve as a history of your database evolution
Prerequisites
Install the Supabase CLI:Creating Your First Migration
Step 1: Initialize Supabase
supabase folder with:
supabase/migrations/- Migration filessupabase/seed.sql- Seed datasupabase/config.toml- Configuration
Step 2: Create a Migration
Step 3: Write the Migration
Edit the migration file:supabase/migrations/20241205075911_create_employees_table.sql
Step 4: Apply the Migration
Real Example: Creating Tables
Here’s a real migration from the Supabase source:supabase/migrations/20241205075911_create_employees_table.sql
Adding Columns
Create a new migration to modify existing tables:supabase/migrations/20241205080043_add_department_to_employees.sql
Real Example: Error Tracking Tables
From Supabase source - creating a content schema with error tracking:Real Example: Vector Search
From Supabase source - setting up pgvector for AI embeddings:supabase/migrations/20230126220613_doc_embeddings.sql
Seeding Data
Create a seed file for initial data:supabase/seed.sql
Using Dashboard to Generate Migrations
Create tables in the Dashboard, then generate migration:supabase/migrations/[timestamp]_create_products_table.sql
Migration Patterns
Adding Indexes
Adding Foreign Keys
Renaming Columns
Dropping Columns Safely
Changing Column Types
Deploying Migrations
Deploy to Supabase Cloud
CI/CD Integration
.github/workflows/deploy.yml
Rolling Back Migrations
Migration to undo changes
Migration Best Practices
Use IF EXISTS / IF NOT EXISTS
Use IF EXISTS / IF NOT EXISTS
Makes migrations idempotent and safe to re-run:
Include rollback migrations
Include rollback migrations
Always know how to undo a migration if needed.
Test migrations locally first
Test migrations locally first
Use
supabase db reset to test the full migration sequence.Keep migrations focused
Keep migrations focused
One migration should do one thing. Split complex changes into multiple migrations.
Add comments
Add comments
Explain why a migration was needed:
Use transactions
Use transactions
Migrations run in transactions by default. For explicit control:
Common Migration Tasks
Enable Extensions
Create Schemas
Set Up Row Level Security
Create Functions and Triggers
Troubleshooting
Lock Timeout Errors
Migration Conflicts
Reset Local Database
Next Steps
Tables
Learn how to design effective table structures
Functions
Create database functions in migrations
CLI Reference
Complete Supabase CLI documentation
Local Development
Set up local development workflow
