Suppose I have the following table
name | genre
---------------------
book 1 | scifi
book 2 | horror
book 3 | scifi
book 4 | romance
book 5 | horror
How can I sort the table above by "genre" in SQL
to get the following results. Please note the order. It's H S R, and not H R S. Is it possible to achieve this without using UNION
?
name | genre
------------------------
book 2 | horror
book 5 | horror
book 1 | scifi
book 3 | scifi
book 4 | romance
Edit: There are only 3 genres.
You could use the field function to customise the sort order
SELECT * FROM `table` ORDER BY FIELD(`genre`, 'horror', 'scifi', 'horror'), `name`;
Try:
select * from table order by case when genre="romance" then 1 else 0 end, genre;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With