Quantcast
Channel: mgalalm » SQL
Viewing all articles
Browse latest Browse all 6

Custom order by order by field

$
0
0

The traditional way  in mysql for ordering the result is ascending  or descending, however there are time you need to order record by a different way.

Suppose you have a table of users and you want to sort the users by their role in another tables so that the administrators come at the top of the list then the editors and all roles sorted alphabetically ascending after that.

Trying accomplish that with the traditional order by won’t be possible since there are roles starts have position between the administrator and editor like author and blogger.

However MySQL has an FIELD function which can be used to accomplish this as below:

SELECT name, role FROM users ORDER BY FIELD(role, ‘editor’, ‘administrator’ ) DESC , role;

|administrator |
| administrator |
| editor |
| editor |
| editor |
| author |
| author |
| blogger |
| downloads admin |
| webforms results admin |
| webforms results admin |

 

ORDER BY FIELD works by specifying the column to sort by and then the values to sort in order.

 

 

 



Viewing all articles
Browse latest Browse all 6

Latest Images

Trending Articles





Latest Images