0

If I have a table User.

At first, it has 2 columns phone, address

Later I need to a an new column name,

How could I add the new column and put the new column in first position.

I know how to add a new column

add_column :users, :name, :string

But not knowing how to change its order.

Because it will append to the last position by default.

I read a book 'head first SQL'

It told me , it's a better practice to put your primary key in the first position

newBike
  • 14,385
  • 29
  • 109
  • 192
  • 1
    https://wiki.postgresql.org/wiki/Alter_column_position Why do you want to change columns position? – Marek Lipka Nov 12 '14 at 08:14
  • possible duplicate of [Is it possible to change the natural order of columns in Postgres?](http://stackoverflow.com/questions/126430/is-it-possible-to-change-the-natural-order-of-columns-in-postgres) – Vivek S. Nov 12 '14 at 08:15
  • 2
    I really wonder Why do you want to change columns position? just curious to know why?? – Vivek S. Nov 12 '14 at 08:17
  • @varchar hi I updated it – newBike Nov 12 '14 at 08:23
  • 1
    Your primary key by default (and by convention) is `id` and it is in first position. – Marek Lipka Nov 12 '14 at 08:25
  • 1
    So, you created a table without a primary key? I hope you are in an early development phase & I suggest you to just drop your table, think about your domain model again & recreate it, when you have finished designing your tables. – pozs Nov 12 '14 at 08:37
  • 2
    Code that relies on ordinal positions of columns is IMO broken code. – Craig Ringer Nov 12 '14 at 08:44
  • 1
    I often change a column's position after I add a new column - not for any technical reason, just because it makes it easier to understand the table when you look at it in the sql terminal. – Max Williams Nov 12 '14 at 12:17

2 Answers2

1

Use the :first option

add_column :users, :name, :string, :first => true
karlingen
  • 13,800
  • 5
  • 43
  • 74
0

You can use :after in rails to position your columns like this:

add_column :users, :name, :string, :after => :id #primary_key
Choco
  • 1,054
  • 1
  • 7
  • 20