I want to use a SELECT query with an IN clause, as well as Order by value same as IN clause
Query:
select *
from table
where column_xyz IN ('124','225','111') // Here values must be in single quotes in query
Output needs to be fetched : 124,225,111
Tried query :
select *
from table
where column_xyz IN ('124','225','111') order by field(column_xyz,'124','225','111')
In mysql we have option called ‘FIELD’ but for postgres I am unable to work with ‘FIELD’ i.e it didn’t work
2
Answers
As you pointed out, Postgres does not directly support any function like MySQL’s
FIELD()
function. The canonical way to do this in ANSI SQL uses aCASE
expression in theORDER BY
clause:In case you actually need to sort many more than 3 possible
xyz
values, then you should maintain a table which maps eachxyz
value to its sort order:Then, join to this table and use the
ord
column to sort your original query: