Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter PostgreSQL column from integer to decimal

Tags:

Thanks to a last minute client request a integer field in our database now needs to be a decimal, to two points.A value of 23 should become 23.00.

Is there a nice way I can convert the table and cast the data across?

I'll freely admit, I haven't done anything like this with PostgreSQL before so please be gentle with me.

like image 540
Oli Avatar asked Jun 26 '11 17:06

Oli


People also ask

How do I change the datatype of a column in PostgreSQL?

First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.

How do you change column type to numeric in PostgreSQL?

So this might work (depending on your data): alter table presales alter column code type numeric(10,0) using code::numeric; -- Or if you prefer standard casting... alter table presales alter column code type numeric(10,0) using cast(code as numeric);

How do I change precision in PostgreSQL?

Try this: ALTER Table account_invoice ALTER COLUMN amount_total TYPE DECIMAL(10,5); DECIMAL(X, Y) -> X represents full length and Y represents precision of the number.

How do I change the datatype size in PostgreSQL?

How to increase the length of a character varying datatype in Postgres without data loss. Run the following command: alter table TABLE_NAME alter column COLUMN_NAME type character varying(120); This will extend the character varying column field size to 120.


1 Answers

Something like this should work:

alter table t alter column c type decimal(10,2);

Edit:

As @Oli stated in the comments; the first number is the entire length of the number (excluding the point) so the maxval for (10,2) would be 99999999.99

like image 181
Szymon Lipiński Avatar answered Oct 24 '22 07:10

Szymon Lipiński