How to delete/drop table?

This is my migration. And it is one of the tables in my database. I no longer need this table. Can I know what is the command I use to remove this table? or can I know where I can find commands to delete/remove migrations?

defmodule Blogs.Repo.Migrations.CreatePosts do
  use Ecto.Migration

  def change do
    create table(:posts) do
      add :title, :string, null: false
      add :slug, :string, null: false
      add :body, :string, null: false
    
      timestamps()
    end

    create unique_index(:posts, [:title])
    create unique_index(:posts, [:slug])
  end
end

Thanks :smiley:

drop table("posts")

drop index("posts", [:title])
drop index("posts", [:slug])

https://hexdocs.pm/ecto_sql/Ecto.Migration.html#drop/1

3 Likes

As a minor note, dropping the indexes is unnecessary, they will be removed when the table they are built for is deleted.

4 Likes

can I know where I should write this? does this work from terminal?

You’ll need to make a new migration file with a different name, and you can use the same format as you posted in the OP. Then run it with mix ecto.migrate

More details at Ecto.Migration

1 Like

No, you have to create a new migration, I named it DropPosts here but you can use any name you like.

To generate migration type the following command in terminal. More about it here mix ecto.gen.migration — Ecto SQL v3.6.1

mix ecto.gen.migration drop_posts

And then add change function to the migration file

defmodule Blogs.Repo.Migrations.DropPosts do
  use Ecto.Migration

  def change do
    drop table("posts")
  end
end
2 Likes

Thanks, that helped!