Typecast string to integer
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.
Solution 1:
Wild guess: If your value is an empty string, you can use NULLIF to replace it for a NULL:
SELECT
NULLIF(your_value, '')::int
Solution 2:
You can even go one further and restrict on this coalesced field such as, for example:-
SELECT CAST(coalesce(<column>, '0') AS integer) as new_field
from <table>
where CAST(coalesce(<column>, '0') AS integer) >= 10;
Solution 3:
If you need to treat empty columns as NULL
s, try this:
SELECT CAST(nullif(<column>, '') AS integer);
On the other hand, if you do have NULL
values that you need to avoid, try:
SELECT CAST(coalesce(<column>, '0') AS integer);
I do agree, error message would help a lot.