group of people choosing books

🐬 MySQL Order By Priority

Today I have been faced on situation where I need to display a list of users ordered by their name and their level. My table looks like below

idfirst_namelast_naelevel
1MuhammadSalahplayer
2JokoToleadmin
3CristioanoRonaldoplayer
4ZlatanIbrahimovicplayer
5JoseMourinhocoach
6MesutOzilplayer
7PepGuardiolacoach
8EdenHazardplayer
9PetrCechassistant manager
example table

My task is to show the table sorted by name, but give a priority order as: admin, coach, assistant manager, player.

You know we just can not order by level column since the result will sorted alphabetically.

Using FIND_IN_SET Function

FIND_IN_SET is a string function I use to this solution. As documented on the page that:

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by , characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (,) character.

MySQL official documentation

So instead of SELECT * FROM users ORDER BY first_name ASC, level ASC

My query should like this:

SELECT * 
FROM users
ORDER BY
    FIND_IN_SET(users.level, 'admin,coach,assistant manager,player'),
    first_name ASC

And the result as expected:

idfirst_namelast_namelevel
2JokoToleadmin
5JoseMourinhocoach
7PepGuardiolacoach
9PetrCechassistant manager
3CristianoRonaldoplayer
8EdenHazardplayer
6MesutOzilplayer
1MuhammadSalahplayer
4ZlatanIbrahimovicplayer
Final Result

Happy querying 🎉🎉

Leave a Reply

Your email address will not be published. Required fields are marked *