Our table is looking good so far, but there is still something missing. We didn’t add any indexes, which will slow down our queries substantially. Let’s fix that now.

Edit a migration or create a new one?

This change raises interesting questions. Should we generate a new migration to add these indexes, or should we edit the migration we already made?

Generally, it’s OK to edit an existing migration provided that we haven’t already committed our migration to source control. Once our migration is available to other developers on our team, we shouldn’t make any edits to it. We should create a new migration with the changes we want to make.

The reason is a practical one. Once migration is committed, we can’t ensure that other developers haven’t already pulled it down and run it on their machines. Ecto can’t detect changes to a migration that’s already been run, so our teammates won’t be able to apply our new changes just by running mix ecto.migrate. We would need to go to them directly and tell them to roll back that migration, pull down our changes, and then rerun the migration (this is usually not a pleasant conversation—trust us on this one). If we need to instead create a new migration, they need to sync their codebase, run the new migration, and they’re back on track.

Change an existing table

To get more practice generating migrations, let’s assume that we’ve already committed to our previous migration, so we’ll create a new one to add our indexes. Let’s say we want to query this table by title and year to add indexes for those two columns.

First, we’ll run mix ecto.gen.migration as we did before, like so:

Get hands-on with 1200+ tech skills courses.