This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Phoenix Ecto Migrations Cheatsheet

A quick reference guide for Phoenix Ecto migrations: creating tables, column types, references, composite indices, timestamps, and raw SQL execution.

· Published

Ecto.Migration provides a database-independent DSL for writing and running migrations in Phoenix and Elixir applications.

CLI Migration Commands

# Generate migration file
mix ecto.gen.migration add_status_to_orders

# Run pending migrations
mix ecto.migrate

# Roll back the most recent migration step
mix ecto.rollback

# Check migration status
mix ecto.migrations

Table Definition DSL

defmodule MyApp.Repo.Migrations.CreateDocuments do
  use Ecto.Migration

  def change do
    create table(:documents) do
      add :title, :string, size: 100, null: false
      add :body, :text
      add :price, :decimal, precision: 10, scale: 2
      add :views, :integer, default: 0
      add :active, :boolean, default: true, null: false
      add :metadata, :map # JSON / JSONB
      add :published_at, :utc_datetime

      # Foreign key reference
      add :author_id, references(:users, on_delete: :delete_all), null: false

      timestamps() # Adds inserted_at and updated_at
    end
  end
end

Modifying Existing Tables (alter)

alter table(:documents) do
  add :subtitle, :string
  modify :title, :string, size: 255
  remove :views
end

Indices & Constraints

# Unique index
create unique_index(:users, [:email])

# Composite index with concurrent creation (PostgreSQL)
create index(:orders, [:user_id, :status], concurrently: true)

# Drop index
drop index(:orders, [:status])

Raw SQL Execution

# Execute arbitrary SQL commands in migration
execute "CREATE EXTENSION IF NOT EXISTS citext;"

References

Related topics