I have a small table and a certain field contains the type "character varying". I'm trying to change it to "Integer" but it gives an error that casting is not possible.
Is there a way around this or should I just create another table and bring the records into it using a query.
The field contains only integer values.
If you've accidentally or not mixed integers with text data you should at first execute below update command (if not above alter table will fail):
There is no implicit (automatic) cast from
text
orvarchar
tointeger
(i.e. you cannot pass avarchar
to a function expectinginteger
or assign avarchar
field to aninteger
one), so you must specify an explicit cast using ALTER TABLE ... ALTER COLUMN ... TYPE ... USING:Note that you may have whitespace in your text fields; in that case, use:
to strip white space before converting.
This shoud've been obvious from an error message if the command was run in
psql
, but it's possible PgAdmin-III isn't showing you the full error. Here's what happens if I test it inpsql
on PostgreSQL 9.2:Thanks @muistooshort for adding the
USING
link.See also this related question; it's about Rails migrations, but the underlying cause is the same and the answer applies.
You can do it like:
or try this:
If you are interested to find more about this topic read this article: https://kolosek.com/rails-change-database-column
If you are working on development environment(or on for production env. it may be backup your data) then first to clear the data from the DB field or set the value as 0.
UPDATE table_mame SET field_name= 0;
After that to run the below query and after successfully run the query, to the schemamigration and after that run the migrate script.
ALTER TABLE table_mame ALTER COLUMN field_name TYPE numeric(10,0) USING field_name::numeric;
I think it will help you.
Try this, it will work for sure.
When writing Rails migrations to convert a string column to an integer you'd usually say:
However, PostgreSQL will complain:
The "hint" basically tells you that you need to confirm you want this to happen, and how data shall be converted. Just say this in your migration:
The above will mimic what you know from other database adapters. If you have non-numeric data, results may be unexpected (but you're converting to an integer, after all).
I got the same problem. Than I realized I had a default string value for the column I was trying to alter. Removing the default value made the error go away :)