MySQL: ORDER BY anyField ASC [with first row X]?

How can I order my result set, but also have a specific row (s fieldX = Y) that will be the first?

+3
source share
2 answers

Something like this should work:

ORDER BY (fieldX = Y) DESC, whateverField ASC
+3
source
select tbl.*, if(fieldX = Y, 1, 0) as custom_sort 
from tbl
order by custom_sort desc, fieldZ asc

Now, whatever the Z field, the row with the X = Y field will always be the first in the result set

+2
source

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


All Articles