Skip to content

Elixir Ecto — Database Queries, Schemas, Migrations, and Repos

DodaTech Updated 2026-06-29 1 min read

In this tutorial, you will learn about Elixir Ecto. We cover key concepts, practical examples, and best practices to help you master this topic.

Ecto is Elixir's database wrapper and query generator. It provides schemas (data mapping), changesets (validation), migrations (schema evolution), and composable queries.

Schema

defmodule MyApp.User do
  use Ecto.Schema

  schema "users" do
    field :name, :string
    field :email, :string
    field :age, :integer, default: 0
    timestamps()
  end

  def changeset(user, attrs) do
    user
    |> Ecto.Changeset.cast(attrs, [:name, :email, :age])
    |> validate_required([:name, :email])
    |> validate_format(:email, ~r/@/)
    |> validate_number(:age, greater_than_or_equal_to: 0)
  end
end

Queries

import Ecto.Query

# Get all
MyApp.Repo.all(User)

# Filter
query = from(u in User, where: u.age >= 18, select: u.name)
MyApp.Repo.all(query)

# Pipe macro style
User
|> where([u], u.age >= 18)
|> order_by([u], desc: u.age)
|> limit(10)
|> MyApp.Repo.all()

Migrations

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

  def change do
    create table(:users) do
      add :name, :string, null: false
      add :email, :string, null: false
      add :age, :integer, default: 0

      timestamps()
    end

    create unique_index(:users, [:email])
  end
end

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro