Re: Dynamic expressions set in "order by" clause

From: "Vyacheslav Kalinin" <vka(at)mgcp(dot)com>
To: "Erik Jones" <erik(at)myemma(dot)com>
Cc: "Sergey Konoplev" <gray(dot)ru(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: Dynamic expressions set in "order by" clause
Date: 2007-11-21 16:59:53
Message-ID: 9b1af80e0711210859x4d7288a2s3d5fc6063c17deb7@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

You could write a set of expressions that yield proper order by field
in one case and say null in another. Say we want order by columns
<col1, col2 desc> if the first function argument is '1' and by <col3
desc, col1, col2> if it is '2', this can be achieved as:

select col1, col2, col3 from mytable
where ...
order by case when $1 = '1' then col1 end,
case when $1 = '1' then col2 else col3 end desc,
case when $1 = '2' then col1 end,
case when $1 = '2' then col2 end
;

This would work as following when $1 = '1':
select col1, col2, col3 from mytable
where ...
order by col1, col2desc, null, null;

and when $1 = '2':
select col1, col2, col3 from mytable
where ...
order by null, col3 desc, col1, col2

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message SHARMILA JOTHIRAJAH 2007-11-21 17:01:50 Re: Postgres table size
Previous Message Richard Huxton 2007-11-21 16:49:25 Re: loading a funtion script from a file