Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL Convert column from integer to text

Tags:

I have a PostgreSQL (9.0) database with a column card_id which is currently of type integer

I need to change this to type text

What is the most best way to achieve this?

The only solution I can find involves creating a temporary column, dropping the original then renaming, I thought they might be a better method??

like image 453
DaveB Avatar asked Dec 01 '11 14:12

DaveB


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 I cast type in PostgreSQL?

PostgreSQL supports a CAST operator that is used to convert a value of one type to another. Syntax: CAST ( expression AS target_type ); Let's analyze the above syntax: First, specify an expression that can be a constant, a table column, an expression that evaluates to a value.

How do I convert text to numeric in PostgreSQL?

Discussion: Use the :: operator to convert strings containing numeric values to the DECIMAL data type. In our example, we converted the string ' 5800.79 ' to 5800.79 (a DECIMAL value). This operator is used to convert between different data types.

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.


2 Answers

Have you tried what the fine manual suggests:

ALTER TABLE table ALTER COLUMN anycol TYPE anytype; 

Depending on the current and the new type you may need to add USING ... to this statement. But in your specific case that should not be necessary I believe.

like image 61
Milen A. Radev Avatar answered Sep 27 '22 22:09

Milen A. Radev


ALTER TABLE table ALTER COLUMN card_id SET DATA TYPE text; 
like image 27
Michael Krelin - hacker Avatar answered Sep 27 '22 21:09

Michael Krelin - hacker