X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [64.117.224.193]) by svr1.postgresql.org (Postfix) with ESMTP id 4A84D30FFE4 for ; Tue, 1 Jul 2003 20:23:30 +0000 (GMT) Received: from svr1.postgresql.org ([64.117.224.193]) by localhost (svr1.postgresql.org [64.117.224.193]) (amavisd-new, port 10024) with ESMTP id 20230-02 for ; Tue, 1 Jul 2003 17:23:19 -0300 (ADT) Received: from joeconway.com (66-146-172-86.skyriver.net [66.146.172.86]) by svr1.postgresql.org (Postfix) with ESMTP id 2077E310CDF for ; Tue, 1 Jul 2003 17:23:19 -0300 (ADT) Received: from [192.168.5.3] (account jconway HELO joeconway.com) by joeconway.com (CommuniGate Pro SMTP 4.0.6) with ESMTP-TLS id 1816708; Tue, 01 Jul 2003 12:53:21 -0700 Message-ID: <3F01ED9F.3060704@joeconway.com> Date: Tue, 01 Jul 2003 13:22:55 -0700 From: Joe Conway User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.3) Gecko/20030312 X-Accept-Language: en-us, en MIME-Version: 1.0 To: Greg Stark Cc: Josh Berkus , Stefan Bill , pgsql-sql@postgresql.org Subject: Re: LEAST and GREATEST functions? References: <20030630201057.14507.qmail@web13905.mail.yahoo.com> <200306302032.23113.josh@agliodbs.com> <87d6gu2otf.fsf@stark.dyndns.tv> In-Reply-To: <87d6gu2otf.fsf@stark.dyndns.tv> Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit X-Archive-Number: 200307/22 X-Sequence-Number: 14136 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