A set knows no order per se. A SELECT
query needs ORDER BY
to return ordered rows.
Other answers have suggested CASE
statements or boolean expressions in your ORDER BY
, but that's far from elegant and rather inefficient with big tables. I suggest to use an array or a comma-separated string instead of a set for your query.
For a given table:
CREATE TABLE tbl (col int);
Using an array it can work like this:
SELECT col
FROM tbl
JOIN (
SELECT col, row_number() OVER () AS rn
FROM unnest('{1,5,3}'::int[]) AS col
) u USING (col)
ORDER BY rn;
Returns all rows found in the sequence of the input array:
-> SQLfiddle
For more details and future-proof code consider this closely related question:
PostgreSQL unnest() with element number
Or the corresponding question on dba.SE:
How to preserve the original order of elements in an unnested array?