TransWikia.com

Troubled trying to convert a column data type in pgAdmin from varchar to integer (SQL state: 22P02)

Stack Overflow Asked by Majid on February 4, 2021

I am simply trying to convert a column with character varying data type to integer by run this bit of Postgres script:

ALTER TABLE tbl.test ALTER COLUMN "XX" TYPE integer USING ("XX"::integer);

and I get this error:

ERROR: invalid input syntax for integer: "XX" SQL state: 22P02

Can someone help me to resolve this issue, please?

One Answer

Based on the error you get it looks like you have some values in XX that cannot be converted to an integer. You will need to correct those values before issuing the alter table.

Find your incorrect values with this query:

select "XX" from tbl.test where "XX" !~ '^-{0,1}d+$';

The !~ is the NOT regex match. The regex anchors to the beginning of the value with ^, accounts for an optional minus sign with -{0,1}, which matches zero or one hyphen character, and then insures that the remaining characters to the end of the value are all digits with d+$.

Any values of XX that fail to match this pattern will be retrieved, and you can figure out how to deal with them either by updating the table or modifying the using part of your alter table.

Answered by Mike Organek on February 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP