How to change datatype of column with data

Create a temporary column with the correct data type, copy the data to the new column, drop the old column, rename the new column to match what the old column was named.

ALTER TABLE call_log ADD (duration_temp NUMBER);
UPDATE call_log SET duration_temp = duration;
ALTER TABLE call_log DROP COLUMN duration;
ALTER TABLE call_log RENAME COLUMN duration_temp TO duration;

The idea for this answer came from Oracle's forums.


the previous solution is excellent, however if you don't want to change the columns orders in call_log table structure, then the following steps are for this:

create table temp_call_log  as select * from call_log; /* temp backup table for call_log */
UPDATE call_log SET duration = null;
/*check,... be sure.... then commit*/
commit;
ALTER TABLE call_log MODIFY duration NUMBER;
UPDATE call_log c SET c.duration = (select t.duration from temp_call_log t where t.primarykey_comumn = c.primarykey_column);
/*check,... be sure.... then commit*/
commit;
drop table temp_call_log;

note1: change primarykey_comumn with primary key in table call_log.

note2: this solution assumes that your data size is not big.


The best solution to preserve the original order of columns: create a temp column, copy the data to it, set the original column to null, modify its type, set the data from temp column back to it and drop the temp column:

ALTER TABLE call_log ADD duration_temp NUMBER;
UPDATE call_log SET duration_temp = duration;
UPDATE call_log SET duration = NULL;
ALTER TABLE call_log MODIFY duration NUMBER;
UPDATE call_log SET duration = duration_temp;
ALTER TABLE call_log DROP (duration_temp);

Tags:

Sql

Oracle