Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid Sorting by the MYSQL IN Keyword

When querying the db for a set of ids, mysql doesnot provide the results in the order by which the ids were specified. The query i am using is the following:

SELECT id ,title, date FROM Table WHERE id in (7,1,5,9,3)

in return the result provided is in the order 1,3,5,7,9.

How can i avoid this auto sorting

like image 238
Nauman Bashir Avatar asked Dec 12 '22 18:12

Nauman Bashir


1 Answers

If you want to order your result by id in the order specified in the in clause you can make use of FIND_IN_SET as:

SELECT id ,title, date 
FROM Table 
WHERE id in (7,1,5,9,3)
ORDER BY FIND_IN_SET(id,'7,1,5,9,3')
like image 177
codaddict Avatar answered Dec 30 '22 10:12

codaddict