Ruby Journal

How to Add New Column After Existing Column With MySQL in Rails?

| Comments

By default, SQL ADD COLUMN would add new column to the tail of columns. What if you want to add a new column and append this new column after an existing column? Read on and I’ll show you how to do that with Rails in MySQL

Add new column after existing column in SQL

MySQL provides AFTER contrainst for ADD COLUMN:

1
2
3
ALTER TABLE mytable
ADD COLUMN  new_column <type>
AFTER       existing_column

The example above tell MySQL to create new new_column after existing_column.

Doing it with Rails migration

With Rails, we could use ActiveRecord::Migration helper for the job. Let’s create a new migration with content:

1
2
3
def change
  add_column :mytable, :new_column, after: 'existing_column'
end

OR if you prefer the SQL way:

1
2
3
def change
  add_column :mytable, :new_column, '<type> AFTER existing_column'
end

That’s all for today folks

Comments