Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a column in a specific position in oracle without dropping and recreating the table?

I have a specific scenario where i have to insert two new columns in an existing table in Oracle. I can not do the dropping and recreating the table. So can it be achieved by any means??

like image 747
Amit Avatar asked Mar 22 '11 12:03

Amit


People also ask

How do I add a column to a specific position in Oracle?

The position of the column cannot be specifically given. If you need a column list in a certain order, then use a view. SELECT * FROM table_x ; new_col will appear last.

How do you add a column to a specific position in an existing table?

To add a column at a specific position within a table row, use FIRST or AFTER col_name . The default is to add the column last. You can also use FIRST and AFTER in CHANGE or MODIFY operations to reorder columns within a table.

Can we add column to the existing table in Oracle?

Note that you cannot add a column that already exists in the table; trying to do so will cause an error. In addition, the ALTER TABLE ADD column statement adds the new column at the end of the table.

Can we change position of column in Oracle?

For certain tables, you can change the order in which columns are displayed by clicking and dragging a column heading to a new position. In other tables, you can use the Reorder Columns dialog to change the position of the columns.


1 Answers

Amit-

I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:

CREATE TABLE MY_TEMP_TABLE AS SELECT * FROM TABLE_TO_CHANGE; 

Drop the table you want to add columns to:

DROP TABLE TABLE_TO_CHANGE; 

It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".

Now insert the data back into the new table:

INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4)  SELECT COL1, 'Foo', 'Bar', COL4 FROM MY_TEMP_TABLE; 

When the data is inserted into your "new-old" table, you can drop the temp table.

DROP TABLE MY_TEMP_TABLE; 

This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.

-CJ

like image 130
CJ Travis Avatar answered Oct 26 '22 13:10

CJ Travis