balexandre
balexandre

Reputation: 75073

How do we "order by" filtering order

What is the trick that we can do in order to a SQL Query be ordered by the ID's we inject in the in clause?

like:

select oh.orderID, oh.orderType, oh.state, oh.orderDateTime
from orderHeaders oh 
where oh.orderID in (
47185154,
47185121,
47184971,
47863101)

my orderID field comes like:

47184971...
47863101...
47185121...
47185154...

how can get the result ordered by the entries ordering in the WHERE IN (...) filter?

Upvotes: 1

Views: 38

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269623

You can use field():

select oh.orderID, oh.orderType, oh.state, oh.orderDateTime
from orderHeaders oh 
where oh.orderID in (47185154, 47185121, 47184971, 47863101)
order by field(oh.orderID, 47185154, 47185121, 47184971, 47863101);

Upvotes: 1

beejm
beejm

Reputation: 2481

You can define them in the order by clause

ORDER BY
CASE oh.OrderID 
WHEN '47185154' THEN 1
WHEN '47185121' THEN 2
WHEN '47184971' THEN 3
WHEN '47863101' THEN 4
ELSE 5
END

Upvotes: 0

Related Questions