Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change column datatype from Text to Integer in PostgreSQL [duplicate]

I am using the following query to change the data type of a column from text to integer but getting error:

 alter table a.attend alter column terminal TYPE INTEGER ; 

ERROR: column "terminal" cannot be cast automatically to type integer

like image 262
Newbie Avatar asked Oct 18 '14 11:10

Newbie


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.

Which one is correct altering a column in PostgreSQL?

The syntax to modify a column in a table in PostgreSQL (using the ALTER TABLE statement) is: ALTER TABLE table_name ALTER COLUMN column_name TYPE column_definition; table_name. The name of the table to modify.

Is int and integer same in PostgreSQL?

There are three kinds of integers in PostgreSQL: Small integer ( SMALLINT ) is 2-byte signed integer that has a range from -32,768 to 32,767. Integer ( INT ) is a 4-byte integer that has a range from -2,147,483,648 to 2,147,483,647.


1 Answers

create table test(id varchar ); insert into test values('1'); insert into test values('11'); insert into test values('12');  select * from test   --Result--  id  character varying --------------------------  1  11  12 

You can see from the above table that I have used the data type – character varying for id column. But it was a mistake because I am always giving integers as id. So using varchar here is a bad practice. So let’s try to change the column type to integer.

ALTER TABLE test ALTER COLUMN id TYPE integer; 

But it returns:

ERROR: column “id” cannot be cast automatically to type integer SQL state: 42804 Hint: Specify a USING expression to perform the conversion

That means we can’t simply change the data type because data is already there in the column. Since the data is of type character varying Postgres can't expect it as integer though we entered integers only. So now, as Postgres suggested we can use the USING expression to cast our data into integers.

ALTER TABLE test ALTER COLUMN id  TYPE integer USING (id::integer); 

It Works.


So you should use

alter table a.attend alter column terminal TYPE INTEGER  USING (terminal::integer) ; 
like image 94
Vivek S. Avatar answered Oct 02 '22 04:10

Vivek S.