MySQL code to sort by specific value in combination of another field
Posted On at by milanWhile development/querying we lots of times need the records to be sorted in a way that records with specific value of specific field come on top and then all other records sorted by another field ascending or descending.
So following example all records with user name 'Adam' will be on top and then all other users' records sorted ascending based on userID field.
SELECT * FROM users ORDER BY FIND_IN_SET('Adam',userName) DESC, userID ASC
Now as used DESC with find_in_set so all user with name Adam will come on top of the list if you use ASC they all will go on bottom of results array. Also you can think of using Find_in_set statment more than once in a quer, in that case in results sql will sort in a way that it will preffer the find_in_ set statements by their order. Following is another example.
SELECT * FROM users ORDER BY FIND_IN_SET('Adam',userName) DESC, FIND_IN_SET('active',userStatus) DESC, userID ASC