Re: Sorting by the maximum value of two columns

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: David Gaudine <davidg(at)alcor(dot)concordia(dot)ca>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Sorting by the maximum value of two columns
Date: 2005-10-05 00:04:47
Message-ID: 20051005000447.GA20434@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

On Tue, Oct 04, 2005 at 04:59:21PM -0400, David Gaudine wrote:
> I want to use SELECT to view some records sorted (ordered?) by the
> maximum value of two fields. I tried
>
> SELECT * FROM mytable ORDER BY MAX(column1,column2)
>
> but there's no such function. How can I do this?

PostgreSQL 8.1 will have GREATEST and LEAST functions so you'll
be able to do this:

SELECT * FROM mytable ORDER BY GREATEST(column1, column2);

In earlier versions you can easily write your own:

CREATE FUNCTION mygreatest(anyelement, anyelement) RETURNS anyelement AS '
SELECT CASE WHEN $1 > $2 THEN $1 ELSE $2 END;
' LANGUAGE sql IMMUTABLE STRICT;

--
Michael Fuhr

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message mike 2005-10-05 02:26:29 Re: Moving from MySQL
Previous Message Jaime Casanova 2005-10-04 21:51:34 Re: stupid SQL question, how reach different rows of two almost same tables