Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Alter table to convert column type from char to bigint [duplicate]

Tags:

postgresql

Possible Duplicate:
how to change column datatype from character to numeric in postgresql 8.4

If I have a field of type varchar (and all the values are null or string representations of numbers) how do I use alter table to convert this column type to bigint?

like image 606
Lighthart Avatar asked Dec 10 '12 21:12

Lighthart


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.

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.

How do I make a column unique in PostgreSQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in PostgreSQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.


1 Answers

To convert simply by parsing the string (casting):

alter table the_table alter column the_column type bigint using the_column::bigint 

In fact, you can use any expression in terms of the_column instead of the_column::bigint to customise the conversion.

Note this will rewrite the table, locking out even readers until it's done.

like image 184
araqnid Avatar answered Oct 26 '22 15:10

araqnid