Avyakt
Avyakt

Reputation: 315

MySQL, how to sort according to categories?

I know how to select and sort one category separately and how to select and sort all categories according to ASC or DESC. My question is how to select all categories and sort them in the way that for instance fifth category will be on first place and others behind it?

Upvotes: 4

Views: 1435

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

You can use field() function

select *
from categories
order by field(id,5) desc,id

or

select *
from categories
order by id= 5 desc,id

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460028

Presuming that fifth category just means that you want to prefer a specific category like Category-Name, you can use CASE:

SELECT t.*
FROM dbo.Tablename t
ORDER BY CASE WHEN t.Category = 'Category-Name' THEN 0 ELSE 1 END ASC,
         Category ASC

Upvotes: 4

Related Questions