I have a simple SQL query in PostgreSQL 8.3 that grabs a bunch of comments. I provide a sorted list of values to the IN
construct in the WHERE
clause:
SELECT * FROM comments WHERE (comments.id IN (1,3,2,4));
This returns comments in an arbitrary order which in my happens to be ids like 1,2,3,4
.
I want the resulting rows sorted like the list in the IN
construct: (1,3,2,4)
.
How to achieve that?
I think this way is better :
or if you prefer evil over good:
And here's another solution that works and uses a constant table (http://www.postgresql.org/docs/8.3/interactive/sql-values.html):
But again I'm not sure that this is performant.
I've got a bunch of answers now. Can I get some voting and comments so I know which is the winner!
Thanks All :-)
sans SEQUENCE, works only on 8.4:
Slight improvement over the version that uses a sequence I think:
On researching this some more I found this solution:
However this seems rather verbose and might have performance issues with large datasets. Can anyone comment on these issues?