From: Joe Conway <mail@joeconway.com>
To: Greg Stark <gsstark@mit.edu>
Cc: Josh Berkus <josh@agliodbs.com>
Cc: Stefan Bill <sjb26@yahoo.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: LEAST and GREATEST functions?
Date: Tue, 01 Jul 2003 13:22:55 -0700
Message-ID: <3F01ED9F.3060704@joeconway.com> (raw)
In-Reply-To: <87d6gu2otf.fsf@stark.dyndns.tv>
References: <20030630201057.14507.qmail@web13905.mail.yahoo.com>
<200306302032.23113.josh@agliodbs.com>
<87d6gu2otf.fsf@stark.dyndns.tv>
Greg Stark wrote:
> SELECT greatest(a,b) FROM bar
>
> would return one tuple for every record in the table with a single value
> representing the greater of bar.a and bar.b.
>
> You could define your own functions to do this but it would be tiresome to
> define one for every datatype.
>
In 7.4devel (just starting beta) you can do this:
create or replace function greatest(anyelement, anyelement) returns
anyelement as 'select case when $1 > $2 then $1 else $2 end' language 'sql';
regression=# select greatest(1, 2);
greatest
----------
2
(1 row)
regression=# select greatest('b'::text, 'a');
greatest
----------
b
(1 row)
regression=# select greatest(now(), 'yesterday');
greatest
-------------------------------
2003-07-01 13:21:56.506106-07
(1 row)
The cast to text is needed because 'a' and 'b' are really typed as
unknown, and with polymorphic functions, you need a well defined data type.
So if you had a table:
create table g(f1 text, f2 text);
insert into g values ('a','b');
insert into g values ('c','b');
regression=# select greatest(f1, f2) from g;
greatest
----------
b
c
(2 rows)
Doesn't help for 7.3.x, but at least you know help is on the way ;-)
Of course, you could always just use the case statement.
Joe
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: mail@joeconway.com, gsstark@mit.edu, josh@agliodbs.com, sjb26@yahoo.com
Subject: Re: LEAST and GREATEST functions?
In-Reply-To: <3F01ED9F.3060704@joeconway.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox