typecast string to integer - Postgres

Vijay DJ picture Vijay DJ · May 9, 2012 · Viewed 350.3k times · Source

I am importing data from a table which has raw feeds in Varchar, I need to import a column in varchar into a string column. I tried using the <column_name>::integer as well as to_number(<column_name>,'9999999') but I am getting errors, as there are a few empty fields, I need to retrieve them as empty or null into the new table.

Kindly let me know if there is a function for the same.

Answer

Frank Heikens picture Frank Heikens · May 9, 2012

Wild guess: If your value is an empty string, you can use NULLIF to replace it for a NULL:

SELECT
    NULLIF(your_value, '')::int