1

I tried to alter a column to integer type using the below query postgres.

alter table pm_user alter column testing2 type integer using testing2::integer;

pm_user - table name
testing2 - column name

The above column would be any kind of data type eg: boolean, text, varchar(256).

It gives error as 'ERROR: invalid input syntax for integer: "NULL"' I tried solutions as below based on the previous queries asked in this website but it is not working for me.

alter table pm_user alter column testing2 type integer using (testing2::integer);                                   
alter table pm_user alter column testing2 type integer;            
alter table pm_user alter column testing2 type numeric using (testing2::numeric);         
alter table pm_user alter column testing2 type numeric (10,2);

What is the actual problem? Where it points input as null? which one is taken as null? What solution I can provide. The same query works when I try to change as

alter table pm_user alter column testing2 type text using testing2::text;  
alter table pm_user alter column testing2 type varchar(256)using testing2::varchar(256);

It is also not working for boolean.

1
  • I need to set the default value for integer column as 0 post altering data type to integer. For that purpose, I used the query "alter table pm_user alter column testing2 set default 0;" The above functionality is required for changing the data type of the column dynamically via the application for the requirement. Commented Apr 7, 2016 at 6:08

1 Answer 1

4

The error message indicates that your column contains the string literal 'NULL' instead of a "real" null value. Something like this:

create table pm_user (testing2 varchar);
insert into pm_user (testing2) values ('NULL');

(Note the 'NULL' - that is not the same as NULL)

So the expression to convert the string to a number must take care of that.

The following will convert a varchar column to integer. Any value in that column that is not a proper integer, will be changed to null:

alter table pm_user alter column testing2 type integer 
   using case when testing2 ~ '^[-+0-9]+$' then testing2::integer else null end; 

~ is Postgres' operator for a regular expressions. testing2 ~ '^[0-9]+$' tests if the column only contains numbers.

Sign up to request clarification or add additional context in comments.

2 Comments

This query works but I checked the column and the data in the column is empty for all rows. Why does it shows 'null' then?
What I can do for boolean? Should I set to false or true as in the previous query?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.