19

I am trying to alter a datatype for a derby db column. The current price column is set as DECIMAL(5,0). I would like to alter it to DECIMAL(7,2). I did this :

alter table item alter column price set data type DECIMAL(7,2);

But it did not work, and showing the error:

Error: Only columns of type VARCHAR may have their length altered. 

May I know how is it possible to alter it? Thank you.

jl.
  • 2,209
  • 12
  • 49
  • 61

5 Answers5

30

Here is the Derby SQL script to change column MY_TABLE.MY_COLUMN from BLOB(255) to BLOB(2147483647):

ALTER TABLE MY_TABLE ADD COLUMN NEW_COLUMN BLOB(2147483647);
UPDATE MY_TABLE SET NEW_COLUMN=MY_COLUMN;
ALTER TABLE MY_TABLE DROP COLUMN MY_COLUMN;
RENAME COLUMN MY_TABLE.NEW_COLUMN TO MY_COLUMN;
uı6ʎɹnɯ ꞁəıuɐp
  • 3,431
  • 3
  • 40
  • 49
8

I think you can do like this:

ALTER TABLE SCHEMA.TABLE ALTER "COLUMN-NAME" SET DATA TYPE VARCHAR(255);

(column-Name SET DATA TYPE VARCHAR(integer)) for Datatype String as an example...

perror
  • 7,071
  • 16
  • 58
  • 85
jr1964
  • 81
  • 1
  • 1
  • The catch is that you can only do it if the existing type is sufficiently similar. For instance, if it's already a VARCHAR(128) you can change it to VARCHAR(255). But if it's an INTEGER, you can't change it to a BIGINT, even though this intuitively seems like it should be possible. – Hakanai May 03 '17 at 03:19
  • 2
    This worked perfectly fine for increasing the column size of varchar and lot simpler than the accepted solution. – oneworld May 01 '18 at 18:36
  • Is this safe in production database? I mean will it not destroy the data? thanks! – Eli Apr 17 '20 at 09:42
3

Here's a slightly more complicated way to alter the column's data type in this fashion:

  1. Add a new column, of the desired data type
  2. Issue "update ... set new-column = old-column to copy the data from the old column to the new column
  3. drop the old column
  4. Rename the new column to have the name of the old column.

Slightly more steps, but in the end the effect will be the same.

If you have trouble working out the exact details of the SQL to do this, let us know and we'll help.

Bryan Pendleton
  • 16,128
  • 3
  • 32
  • 56
3

You can alter table like this:

ALTER TABLE [table] ALTER COLUMN [column] SET DATA TYPE [type];

Or in Rails, just use:

change_column :table_name, :column_name, :integer
Aleks
  • 4,866
  • 3
  • 38
  • 69
-3

Posgtes Solution :

ALTER TABLE prices_table ALTER price_column TYPE decimal (7,2 )

Pavunkumar
  • 5,147
  • 14
  • 43
  • 69
  • 1
    I think Derby does not support TYPE, it displays error, Syntax error: Encountered "TYPE" at line 1, column 30. – jl. Mar 05 '10 at 06:53