views:

115

answers:

3

When one uses "ALTER TABLE tab ADD col", the new column gets added to the end of the table. For example:

TABLE: TAB
COL_1 COL_2 COL_4

ALTER TABLE TAB ADD COL_3

table will become

TABLE: TAB
COL_1 COL_2 COL_4 COL_3

However as the naming of my example columns suggests I'd actually like the table to end up like this:

TABLE: TAB
COL_1 COL_2 COL_3 COL_4

With COL_3 before COL_4.

Besides rebuilding the table from scratch, is there any standard SQL that will get the job done? However if there is no standard SQL, I could still use some vendor dependent solutions for Oracle, but again a standard solution would be best.

Thanks.

+7  A: 

By default, columns are only added at the end.

To insert a column in the middle, you have to drop and recreate the table and all related objects (constraints, indices, defaults, relationships, etc).

Several tools do this for you, and depending on the size of the table, this may be an intensive operation.

You may also consider creating views on the table that display columns in the order of preferrence (overriding the actual order in the table).

Raj More
yeah the view solution was what I knew, and was going to be my first attempt, but was kind of hoping for a simpler solution :/
Robert Gould
+1  A: 

http://www.orafaq.com/wiki/SQL_FAQ#How_does_one_add_a_column_to_the_middle_of_a_table.3F says it can't be done, and suggests workarounds of renaming the table and doing a create table as select... or (something I am unfamiliar with) "Use the DBMS_REDEFINITION package to change the structure".

ysth
+1  A: 

ALTER TABLE TABLENAME ALTER COLUMN COLUMNNAME POSITION X;

drorhan
Is `POSITION` specific to MySQL?
Raj More
i use it in Firebird.
drorhan
This works on MySQL too. It's not standard SQL. But the answer might help someone with a similar problem using a DB that supports this
Robert Gould