Ordering mysql results by certain field value first
September 30, 2011
I needed to order a mysql result but in a somewhat custom way.
Say there is a field “id” and rows of values of 8, 4, 2, and 19.
SELECT `id` FROM `table_name` ORDER BY `id`;
This would obviously return the order: 2,4,8,19.
But what if you needed the 4 to be first and then order by integers?
SELECT IF(`id` = '4','0','1') AS `custom_order` FROM `table_name` ORDER BY `custom_order`;
This would return 4,2,8,19.
Simple and can be really helpful.