How to convert a string column type to numeric or bigint in postgresql
Design your own custom cast from string to bigint. Something like this:
CREATE OR REPLACE FUNCTION convert_to_bigint(v_input text)
RETURNS BIGINT AS $$
DECLARE v_bigint_value BIGINT DEFAULT NULL;
BEGIN
BEGIN
v_bigint_value := v_input::BIGINT;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'Invalid bigint value: "%". Returning something else.', v_input;
RETURN 0;
END;
RETURN v_bigint_value;
END;
Then create a new table fixed_table_with_bigint
with the same parameters as the old table except change the string column into the bigint column.
Then insert all the rows from the previous table (using the custom cast convert_to_integer
) into the new table:
insert into fixed_table_with_bigint
select mycolumn1,
convert_to_bigint(your_string_bigint_column),
mycolumn3
from incorrect_table
You may have to modify convert_to_bigint
in order to handle strings which are not numbers, blankstrings, nulls, control characters and other Weirdness.
Then delete the first table and rename the 2nd table as the first table.