mas
mas

Reputation: 1176

SQLite - return sorted list

I can use

SELECT * FROM table 
WHERE id IN (478,278,190,890,123)

to return a list of records.

How can I instruct SQLite to return the records sorted using the order as specified in the list?

Upvotes: 0

Views: 343

Answers (2)

manji
manji

Reputation: 47978

There is no dedicated instruction to such thing. You have to find a solution for each case.

In your example, you can do it like this:

SELECT *
  FROM table
 WHERE id IN (478,278,190,890,123)
 ORDER BY CASE id WHEN 478 THEN 0
                  WHEN 278 THEN 1
                  WHEN 190 THEN 2
                  WHEN 890 THEN 3
                  WHEN 123 THEN 4
          END

But if you have a long list of ids, it will become difficult to maintain.

Upvotes: 3

Vikram
Vikram

Reputation: 7515

you can use order by the field name. In this I am assuming id select * from table where id in (478,278,190,890,123) order by id

Upvotes: 0

Related Questions