Is it possible to define a default value that will be returned in case a CAST operation fails?
For example, so that:
SELECT CAST('foo' AS INTEGER)
Will return a default value instead of throwing an error?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is no default value for a CAST:
There is no room in the syntax for anything other than the expression to be casted and the desired target type.
However, you can do it by hand with a simple function:
Then you can say things like
cast_to_int('pancakes', 0)and get0.PostgreSQL also lets you create your own casts so you could do things like this:
Then you could say
and get
0or you could sayand get
0for thesome_text_columnvalues that aren’t valid integers. If you wanted to castvarchars using this auto-defaulting cast then you’d have to double cast:Just because you can do this doesn’t make it a good idea. I don’t think replacing the standard text to integer cast is the best idea ever. The above approach also requires you to leave the standard
varchartointegercast alone, you could get around that if you wanted to do the whole conversion yourself rather than lazily punting to the built in casting.NULL handling is left as an (easy) exercise for the reader.