30

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?

David Wolever
  • 148,955
  • 89
  • 346
  • 502
  • Changing default/expected behaviour this way strikes me as... dangerous. You want the ability to check the value with something like `IS_NUMERIC()` (SQL Server function), but it doesn't seem to exist for Postgresql (or DB2, in my case). You'd probably be best served by creating a UDF, to which you could also give a default value. – Clockwork-Muse Apr 24 '12 at 22:52
  • 1
    Oh, I don't want to change the functionality - just define a default for that cast (ex, something like `CAST('foo' AS INTEGER DEFAULT -1)` or something. – David Wolever Apr 25 '12 at 01:48

2 Answers2

42

There is no default value for a CAST:

A type cast specifies a conversion from one data type to another. PostgreSQL accepts two equivalent syntaxes for type casts:

CAST ( expression AS type )
expression::type

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:

create or replace function cast_to_int(text, integer) returns integer as $$
begin
    return cast($1 as integer);
exception
    when invalid_text_representation then
        return $2;
end;
$$ language plpgsql immutable;

Then you can say things like cast_to_int('pancakes', 0) and get 0.

PostgreSQL also lets you create your own casts so you could do things like this:

create or replace function cast_to_int(text) returns integer as $$
begin
    -- Note the double casting to avoid infinite recursion.
    return cast($1::varchar as integer);
exception
    when invalid_text_representation then
        return 0;
end;
$$ language plpgsql immutable;

create cast (text as integer) with function cast_to_int(text);

Then you could say

select cast('pancakes'::text as integer)

and get 0 or you could say

select cast(some_text_column as integer) from t

and get 0 for the some_text_column values that aren't valid integers. If you wanted to cast varchars using this auto-defaulting cast then you'd have to double cast:

select cast(some_varchar::text as integer) from t

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 varchar to integer cast 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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Just wondering if you could clarify "*Note the double casting to avoid infinite recursion*"? I would have thought that `$1` was already of type `text/varchar` there. – Bruno Jul 22 '14 at 18:13
  • 1
    @Bruno: The function is `cast_to_int(text)` so `$1` will be `text`, `text` and `varchar` are different types. If we didn't `$1::varchar` then we'd be doing a `cast(text as integer)`. But that cast is implemented by the `cast_to_int` function so `cast_to_int` would end up indirectly calling itself through the custom cast. – mu is too short Jul 22 '14 at 18:24
  • 1
    Ah that's interesting, I was wrongly assuming that `text` and `varchar` would [be the more or less the same](http://stackoverflow.com/a/4849030/372643) there too, but obviously not. – Bruno Jul 22 '14 at 18:28
  • AFAIK the only difference between `text` and `varchar` is at the very edges of PostgreSQL, they're the same once you get past the first couple molecules at surface. There are people around here that know the internal details way better than I ever will. A question about the difference between `text` and `varchar` which references this one and [that one](http://stackoverflow.com/a/4849030/372643) would probably be noticed by [Craig Ringer](http://stackoverflow.com/users/398670/craig-ringer) and [Erwin Brandstetter](http://stackoverflow.com/users/939860/erwin-brandstetter) at least. – mu is too short Jul 22 '14 at 19:15
3

Trap the error as described in documentation and then specify an action to do instead.

Documentation on error trapping for PostgreSQL Snippet included below.

35.7.5. Trapping Errors

By default, any error occurring in a PL/pgSQL function aborts execution of the function, and indeed of the surrounding transaction as well. You can trap errors and recover from them by using a BEGIN block with an EXCEPTION clause. The syntax is an extension of the normal syntax for a BEGIN block:

[ <<label>> ]
[ DECLARE
    declarations ]
BEGIN
    statements
EXCEPTION
    WHEN condition [ OR condition ... ] THEN
        handler_statements
    [ WHEN condition [ OR condition ... ] THEN
          handler_statements
      ... ]
END;

If no error occurs, this form of block simply executes all the statements, and then control passes to the next statement after END. But if an error occurs within the statements, further processing of the statements is abandoned, and control passes to the EXCEPTION list. The list is searched for the first condition matching the error that occurred. If a match is found, the corresponding handler_statements are executed, and then control passes to the next statement after END. If no match is found, the error propagates out as though the EXCEPTION clause were not there at all: the error can be caught by an enclosing block with EXCEPTION, or if there is none it aborts processing of the function.

RThomas
  • 10,702
  • 2
  • 48
  • 61