Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql ORDER BY specific value

Tags:

mysql

Suppose I have the following query:

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

How would I throw a particular name to the front of the order and then do the rest of the ordering, something like:

SELECT id, name FROM table ORDER BY name='david', name
  • 1, David
  • 4, Ashley
  • 1, Anna
  • 3, Zach
like image 828
David542 Avatar asked Oct 28 '14 01:10

David542


1 Answers

You are almost exactly there. You just need desc:

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

MySQL treats booleans as integers, with true being "1" and false being "0". So, when it is true, the value is a "1". To put it first, you need to sort in descending order.

like image 51
Gordon Linoff Avatar answered Sep 23 '22 23:09

Gordon Linoff