Re: Dynamic expressions set in "order by" clause - Mailing list pgsql-general

From Vyacheslav Kalinin
Subject Re: Dynamic expressions set in "order by" clause
Date
Msg-id 9b1af80e0711210859x4d7288a2s3d5fc6063c17deb7@mail.gmail.com
Whole thread Raw
In response to Re: Dynamic expressions set in "order by" clause  (Erik Jones <erik@myemma.com>)
List 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

pgsql-general by date:

Previous
From: Martin Gainty
Date:
Subject: Re: Read-only availability of a standby server?
Next
From: xeb@mail.ru
Date:
Subject: Re: ERROR: invalid restriction selectivity: 224359728.000000