Mysql ORDER BY for a specific value

Suppose I have the following query:

SELECT id, name FROM table ORDER BY name 
  • 4, Ashley
  • 1, Anna
  • 2, David
  • 3, Zack

How would I choose a specific name before the order, and then do the rest of the order, something like:

 SELECT id, name FROM table ORDER BY name='david', name 
  • 1, David
  • 4, Ashley
  • 1, Anna
  • 3, Zack
+5
source share
1 answer

You are almost certainly there. You just need to desc :

 SELECT id, name FROM table ORDER BY (name = 'david') DESC, name; 

MySQL treats boolean variables as integers, with true set to "1" and false to "0". So, when it's true, the value is "1". First of all, you need to sort in descending order.

+8
source

Source: https://habr.com/ru/post/1205653/


All Articles