0

I am using this query to select rows in MySQL

SELECT * FROM `table` WHERE `id` IN (5,2,3,1,4);

Now by default the rows will be ordered by their id: 1, 2, 3, 4, 5

Is there any way that I can order rows as they are in the query, so the order should be: 5, 2, 3, 1, 4 ?

Enve
  • 6,298
  • 10
  • 38
  • 82

2 Answers2

2

Use MySQL's FIELD() function

SELECT * 
  FROM `table` 
 WHERE `id` IN (5,2,3,1,4)
 ORDER BY FIELD(`id`, 5,2,3,1,4)
;
Mark Baker
  • 205,174
  • 31
  • 336
  • 380
2

You can use case statement to customize the sort

SELECT *
FROM   table
WHERE  id IN ( 5, 2, 3, 1, 4 )
ORDER  BY CASE id
            WHEN 5 THEN 1
            WHEN 2 THEN 2
            WHEN 3 THEN 3
            WHEN 1 THEN 4
            WHEN 4 THEN 5
            ELSE 6
          END 
Pரதீப்
  • 88,697
  • 17
  • 124
  • 160