ammar zaheer
ammar zaheer

Reputation: 71

How to modify data type in Oracle with existing rows in table

How can I change DATA TYPE of a column from number to varchar2 without deleting the table data?

Upvotes: 5

Views: 42950

Answers (5)

Dinushika Rathnayake
Dinushika Rathnayake

Reputation: 419

Since we can't change data type of a column with values, the approach that I was followed as below,

Say the column name you want to change type is 'A' and this can be achieved with SQL developer.

First sort table data by other column (ex: datetime). Next copy the values of column 'A' and paste to excel file. Delete values of the column 'A' an commit. Change the data type and commit. Again sort table data by previously used column (ex: datetime). Then paste copied data from excel and commit.

Upvotes: 0

Amit Jain
Amit Jain

Reputation: 41

alter table table_name modify (column_name VARCHAR2(255));

Upvotes: 0

BobC
BobC

Reputation: 4416

The most efficient way is probably to do a CREATE TABLE ... AS SELECT
(CTAS)

Upvotes: 0

Lalit Kumar B
Lalit Kumar B

Reputation: 49062

You have to first deal with the existing rows before you modify the column DATA TYPE.

You could do the following steps:

  1. Add the new column with a new name.
  2. Update the new column from old column.
  3. Drop the old column.
  4. Rename the new column with the old column name.

For example,

alter table t add (col_new varchar2(50));

update t set col_new = to_char(col_old);

alter table t drop column col_old cascade constraints;

alter table t rename column col_new to col_old;

Make sure you re-create any required indexes which you had.

You could also try the CTAS approach, i.e. create table as select. But, the above is safe and preferrable.

Upvotes: 6

Justin Cave
Justin Cave

Reputation: 231651

You can't.

You can, however, create a new column with the new data type, migrate the data, drop the old column, and rename the new column. Something like

ALTER TABLE table_name
  ADD( new_column_name varchar2(10) );

UPDATE table_name
   SET new_column_name = to_char(old_column_name, <<some format>>);

ALTER TABLE table_name
 DROP COLUMN old_column_name;

ALTER TABLE table_name
 RENAME COLUMN new_column_name TO old_coulumn_name;

If you have code that depends on the position of the column in the table (which you really shouldn't have), you could rename the table and create a view on the table with the original name of the table that exposes the columns in the order your code expects until you can fix that buggy code.

Upvotes: 19

Related Questions