jess chavez jess chavez - 4 months ago 11
SQL Question

Custom order by on a column in MySQL

I want to select 3 specific record and the rest should be random.

EX:

Database:Records

1
2
3
4
5
6
7
8
9
10


I want to select
2,5,8
.

Answer

You can achieve this with the help of CASE WHEN and FIND_IN_SET

SELECT 
*
FROM table_jess
ORDER BY 
CASE WHEN FIND_IN_SET(id,'2,5,8') > 0 THEN 0 ELSE id END,id

Please check the WORKING DEMO

EDIT:

If you want random result for the rest of the entries then use the following query:

SELECT 
*
FROM table_jess
ORDER BY 
CASE WHEN FIND_IN_SET(id,'8,2,5') > 0 THEN 0 ELSE RAND() END,id;

WORKING DEMO

Comments