Re: Find min and max values across two columns?

From: "Jim C(dot) Nasby" <jnasby(at)pervasive(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Amos Hayes <ahayes(at)polkaroo(dot)net>, pgsql-sql(at)postgresql(dot)org
Subject: Re: Find min and max values across two columns?
Date: 2006-03-27 13:56:29
Message-ID: 20060327135629.GM80726@pervasive.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Fri, Mar 24, 2006 at 04:00:35PM -0500, Tom Lane wrote:
> Amos Hayes <ahayes(at)polkaroo(dot)net> writes:
> > I'm trying to build a query that among other things, returns the
> > minimum and maximum values contained in either of two columns.
>
> I think you might be looking for
>
> select greatest(max(columnA), max(columnB)) from tab;
> select least(min(columnA), min(columnB)) from tab;
>
> greatest/least are relatively new but you can roll your own in
> older PG releases.

And if you care about performance you might also try:

SELECT max(greatest(column_a, column_b) ...
SELECT min(least(column_a, column_b) ...

There may be a difference in performance between the two.
--
Jim C. Nasby, Sr. Engineering Consultant jnasby(at)pervasive(dot)com
Pervasive Software http://pervasive.com work: 512-231-6117
vcard: http://jim.nasby.net/pervasive.vcf cell: 512-569-9461

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Markus Schaber 2006-03-27 14:00:35 Re: Problem using set-returning functions
Previous Message Jim C. Nasby 2006-03-27 13:52:19 Re: Question about One to Many relationships