yavona
yavona

Reputation: 107

How to order by a specific way?

Mysql table:

id | category    | image<br>
--------------------------------
0  | landscape   | image name
1  | panarimic   | image name
2  | portrait    | image name
3  | landscape   | image name
4  | landscape   | image name
5  | portait     | image name

I want to write mysql select that should get the landscapes first and than list others. How can i do that? i can add category number and make "order by" but is there another way without it?

Upvotes: 2

Views: 70

Answers (2)

vishu
vishu

Reputation: 231

SELECT 
  * 
FROM
  tableName 
ORDER BY 
  CASE
    WHEN category LIKE 'landscape' 
    THEN 1 
    ELSE 0 
  END DESC ;

Upvotes: 0

sagi
sagi

Reputation: 40481

Yes, you can use CASE EXPRESSION in your ORDER BY CLAUSE :

SELECT t.id,t.category,t.image
FROM YourTable t
ORDER BY CASE WHEN t.category = 'landscapes' then 1 else 0 end DESC,
         t.category

Upvotes: 5

Related Questions