2

In PostgreSQL, does this query

SELECT "table".* FROM "table" WHERE "table"."column" IN (1, 5, 3)

always return the results in the 1, 5, 3 order or is it ambiguous?
If it's ambiguous, how do I properly assure the results are in the order 1, 5, 3?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
McFadden
  • 1,610
  • 1
  • 16
  • 19

5 Answers5

3

The WHERE clause will not order the results in any way, it will just select matching records, in whatever order the database index finds them in.

You'll have to add an order by clause.

Greg Olsen
  • 1,370
  • 17
  • 28
2

False orders before true

SELECT "table".*
FROM "table"
WHERE "table"."column" IN (1, 5, 3)
order by
    "column" != 1,
    "column" != 5,
    "column" != 3
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
2

Add something like the following to your select statement

order by CASE WHEN "column"=1 THEN 1
              WHEN "column"=2 THEN 2
              ELSE 3
       END

if you have many more than three values it may be easier to make a lookup table and join to that in you query

Ian Kenney
  • 6,376
  • 1
  • 25
  • 44
1

When you use "IN" in a select statement Postgre just return the matching rows against that range of values. It's not ambiguous in any way but if you need to order the results you need to explicitly add ORDER BY "column1,column2..."

Edgar Sampere
  • 263
  • 4
  • 24
1

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?

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228