In PostgreSQL I have a table with a varchar column. The data is supposed to be integers and I need it in integer type in a query. Some values are empty strings. The followin
@Matthew's answer is good. But it can be simpler and faster. And the question asks to convert empty strings (''
) to 0
, but not other "invalid input syntax" or "out of range" input:
CREATE OR REPLACE FUNCTION convert_to_int(text)
RETURNS int AS
$func$
BEGIN
IF $1 = '' THEN -- special case for empty string like requested
RETURN 0;
ELSE
RETURN $1::int;
END IF;
EXCEPTION WHEN OTHERS THEN
RETURN NULL; -- NULL for other invalid input
END
$func$ LANGUAGE plpgsql IMMUTABLE;
This returns 0
for an empty string and NULL
for any other invalid input.
It can easily be adapted for any data type conversion.
Entering an exception block is substantially more expensive. If empty strings are common it makes sense to catch that case before raising an exception.
If empty strings are very rare, it pays to move the test to the exception clause.