Re: Sql ORDER BY and ASC/DESC question

From: Gregory Stark <stark(at)enterprisedb(dot)com>
To: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>
Cc: <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Sql ORDER BY and ASC/DESC question
Date: 2008-01-30 13:32:45
Message-ID: 87tzkvbfr6.fsf@oxford.xeocode.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

"A. Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com> writes:

> am Wed, dem 30.01.2008, um 11:35:51 +0100 mailte Jaroslav Sivy folgendes:
>> Hello everyone,
>>
>> I have following problem: am using pl/sql functions to trigger some
>> sql code and i need to pass ORDER_BY column name and ASC/DESC sorting
>> order as an input parameters into that function and order the result
>> based on these input parameters.
>>
>> The problem is, that the only way is to create query as "string" and
>> then execute it as "string".
>
> Right.
>>
>> Is there any other way around how to avoid that "string query"?

If you're not concerned with the planner being able to find indexes to satisfy
these orderings (ie, you don't mind always doing a sort) you could do
something like:

ORDER BY
CASE ?
WHEN 1 THEN name ASC
WHEN 2 THEN name DESC
WHEN 3 THEN height ASC
WHEN 4 THEN height DESC
ELSE id ASC
END

But to the planner this will be basically an opaque expression. It won't be
able to use any indexes on these columns. Also, incidentally you might want to
use text strings instead of integer labels.

--
Gregory Stark
EnterpriseDB http://www.enterprisedb.com
Get trained by Bruce Momjian - ask me about EnterpriseDB's PostgreSQL training!

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2008-01-30 18:00:29 Re: Sql ORDER BY and ASC/DESC question
Previous Message Bart Degryse 2008-01-30 12:30:52 Re: Sql ORDER BY and ASC/DESC question