Skip to content

Instantly share code, notes, and snippets.

@iamvery
Created May 8, 2012 18:53
Show Gist options
  • Save iamvery/2638462 to your computer and use it in GitHub Desktop.
Save iamvery/2638462 to your computer and use it in GitHub Desktop.
PostgreSQL function that safely casts a string value to an integer. Useful when sorting string fields as numbers :)
-- Function: "Safe_Cast_Str_to_Int"(character varying, integer)
CREATE OR REPLACE FUNCTION "Safe_Cast_Str_to_Int"(input_string character varying, default_value integer DEFAULT NULL::integer)
RETURNS integer AS
$BODY$
BEGIN
BEGIN
RETURN input_string::integer;
EXCEPTION WHEN data_exception THEN
RETURN default_value;
END;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION "Safe_Cast_Str_to_Int"(character varying, integer) OWNER TO postgres;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment