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?
In Postgres 9.4 or later, this is probably simplest and fastest:
Using the new
WITH ORDINALITY
, that @a_horse already mentioned.We don't need a subquery, we can use the set-returning function like a table.
A string literal to hand in the array instead of an ARRAY constructor may be easier to implement with some clients.
Detailed explanation:
I agree with all other posters that say "don't do that" or "SQL isn't good at that". If you want to sort by some facet of comments then add another integer column to one of your tables to hold your sort criteria and sort by that value. eg "ORDER BY comments.sort DESC " If you want to sort these in a different order every time then... SQL won't be for you in this case.
here, [bbs] is the main table that has a field called ids, and, ids is the array that store the comments.id .
passed in postgresql 9.6
Another way to do it in Postgres would be to use the
idx
function.Don't forget to create the
idx
function first, as described here: http://wiki.postgresql.org/wiki/Array_IndexIn Postgresql:
Just because it is so difficult to find and it has to be spread: in mySQL this can be done much simpler, but I don't know if it works in other SQL.