ORDER BY in prepared statements

From: Bryn Jeffries <bryn(dot)jeffries(at)sydney(dot)edu(dot)au>
To: "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: ORDER BY in prepared statements
Date: 2015-01-21 20:51:23
Message-ID: 7DAF466372B27747B8EA808BE5651FA57AD61AA4@ex-mbx-pro-01
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

In a number of places on the web I've seen it claimed that ordering can be set via prepared statements. Indeed, the expected syntax is accepted on my 9.3 server without errors:

sandbox=# CREATE TABLE test (
id serial PRIMARY KEY,
gender char
);

sandbox=# INSERT INTO test(gender) VALUES('m') VALUES('f') VALUES('m') VALUES('f') VALUES('m');

sandbox=# PREPARE testplan(text) AS
SELECT * FROM test ORDER BY $1;

But the output is not what one would expect:

sandbox=# EXECUTE testplan('gender');
id | gender
----+--------
1 | m
2 | f
3 | m
4 | f
5 | m
6 | f
(6 rows)

As opposed to:
sandbox=# SELECT * FROM test ORDER BY gender;
id | gender
----+--------
2 | f
4 | f
6 | f
1 | m
3 | m
5 | m
(6 rows)

It would seem that the ORDER BY clause is simply ignored in the prepared statement. Is this deliberate behaviour? I can well understand that supporting this kind of query would be tricky, but it would be very handy.

Many thanks,

Bryn

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Paul Jungwirth 2015-01-21 21:06:49 Re: ORDER BY in prepared statements
Previous Message Rob Sargent 2015-01-21 19:51:16 Re: Fwd: Ask for a question