Re: LEAST and GREATEST functions? - Mailing list pgsql-sql

From Joe Conway
Subject Re: LEAST and GREATEST functions?
Date
Msg-id 3F02387A.4070401@joeconway.com
Whole thread Raw
In response to Re: LEAST and GREATEST functions?  (Josh Berkus <josh@agliodbs.com>)
List pgsql-sql
Josh Berkus wrote:
>>create or replace function greatest(anyelement, anyelement) returns
>>anyelement as 'select case when $1 > $2 then $1 else $2 end' language
>>'sql';
> 
> Way cool.  I'd have to imagine that it would blow up if you did this, though:
> 
> select greatest ( 512, now() );
> 
> With an "Operator is not defined" error, hey?

It errors out with a type mismatch error:

regression=# select greatest (512, now());
ERROR:  Function greatest(integer, timestamp with time zone) does not exist
Unable to identify a function that satisfies the given argument types
You may need to add explicit typecasts

Of course none of this is documented yet (because I still owe the 
documentation ;-), but that can be done during feature freeze/beta), but 
the concept of the anyelement data type is that, although it can mean 
literally any data type, any arguments (or return type) so defined have 
to match each other at function call time. So with:  greatest(anyelement, anyelement) returns anyelement
when it gets called, the two arguments *must* be the same data type, and 
the function will return the same type. Any arguments declared with a 
specific datatype (say integer) don't participate in the runtime 
resolution of the polymorphic arguments.

Similarly there is an anyarray data type that is constrained at runtime 
to be an array of anything that was defined as anyelement; e.g.:

create or replace function myelement(anyarray, int) returns anyelement 
as 'select $1[$2]' language 'sql';

regression=# select myelement(array[11,22,33,44,55], 2); myelement
-----------        22
(1 row)

Joe



pgsql-sql by date:

Previous
From: Josh Berkus
Date:
Subject: Re: LEAST and GREATEST functions?
Next
From: Joe Conway
Date:
Subject: Re: passing a record as a function argument in pl/pgsql