Migration vs Schema in Ecto

I’ve read through the Ecto docs (specfically this https://hexdocs.pm/ecto/getting-started.html#setting-up-the-database) and I don’t understand why I create both a migration and a schema.

For example, I created a create_orgs migration:
defmodule MyApp.Repo.Migrations.CreateOrgs do
use Ecto.Migration

def change do
create table(:orgs, primary_key: false) do
add :id, :binary_id, primary_key: true

So I run this when I start the project and it creates the table in Postgres. What part does the Schema play?

For context, I am a new developer and have never built a project from beginning to end before. I ask for your patience with my silly questions.

1 Like


The migration creates the data model (and potentially updates data) on the database server.

The schema (specifically Ecto schema) is a representation of that model within Elixir so that your Elixir code can interact with it. Some systems (e.g. Entity Framework in .Net) can automatically generate migrations from changes detected in the schema, but Ecto can’t. If you don’t use the generators (e.g. mix phx.html.gen) then you have to code both the schema and the migration.

(Just to complicate things, you can also have an Ecto schema with no corresponding tables in the database…)


You can have migration without schema too, in case You create a join table :slight_smile:


Want to add that it is possible to have also multiple schemas for the same table dependind on the context you’re using it. For example some fields or changesets are useful for a specific context and not for another one. Maybe you want also to assign different default value to some fields depending on the context…


Migrations create or modify the tables in the database.

If you are using a legacy database you don’t need the migrations because the tables already exist.