Creating a table

Ecto for Beginners : part 3 of 22 published on Sep 06, 2015

To create tables on our database, we need to use migrations. The easiest way to create a migration is to use the mix task.

$ mix ecto.gen.migration create_posts
* creating priv/repo/migrations
* creating priv/repo/migrations/TIMESTAMP_create_posts.exs

Inside our migration file, we first tell the migration to create the table.

create table(:your_table_name) do

Inside the do/end block is where we add columns to our database table.

create table(:your_table_name) do
  add :your_column_name, :your_column_type

We will create the posts table and add a few columns.

# /priv/repo/migrations/TIMESTAMP_create_posts.exs
defmodule Readdit.Repo.Migrations.CreatePosts do
  use Ecto.Migration

  def change do
    create table(:posts) do
      add :title, :string
      add :votes, :integer
      add :posted_on, :datetime
      add :advertisement_message, :string


After our migration is saved, we can run the migration with the mix task: mix ecto.migrate.

$ mix ecto.migrate
== Running Readdit.Repo.Migrations.CreatePosts.change/0 forward
create table posts
== Migrated in 0.0s
Next: Adding and Removing a column