Why can't a function that accepts an int, be overloaded to accept an interval?

All we need is an easy explanation of the problem, so here it is.

Currently getting an error about type casts,

HINT: Could not choose a best candidate function. You might need to add explicit type casts.

Let’s say I create an overloaded function foo

CREATE FUNCTION foo(x int)
RETURNS int AS $$
  SELECT 1
$$ LANGUAGE sql;

CREATE FUNCTION foo(x interval)
RETURNS int AS $$
  SELECT 2
$$ LANGUAGE sql;

How come when I then call that function,

SELECT foo('5 days');

I get,

ERROR:  function foo(unknown) is not unique
LINE 1: SELECT foo('5 days');
               ^
HINT:  Could not choose a best candidate function. You might need to add explicit type casts.

Question inspired by looking into generate_series and the conversations on irc.freenode.net/#postgresql

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The reason for this is because '5 days' at that point is essentially '5 days'::unknown. From there the question is whether the right option is

  • '5 days'::int or
  • '5 days'::interval

Sure, '5 days'::int isn’t valid, but unknown -> int is required so you can say SELECT '5' + 5;. PostgreSQL doesn’t know that “5 days” will throw an exception until after it tries and because both are typed the same it just gives up rather than guessing randomly.

There is no good work around to this.

You can see it documented under Functions: Type Conversion

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply