Search Postgresql Archives

Re: Dynamic expressions set in "order by" clause

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

---------------------------(end of broadcast)---------------------------
TIP 3: Have you checked our extensive FAQ?

               http://www.postgresql.org/docs/faq

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux