Arm Peev
Arm Peev

Reputation: 128

How to sort mysql result but show specific result first

I have table like this one

id    name
1     John
2     Mike
3     Zed
4     Teacher
5     Aaron
...........

How to make mysql query to get rows in ASC order by name but put "Teacher" at the top or something that starts with "Teacher"?

Upvotes: 3

Views: 184

Answers (3)

AdrianBR
AdrianBR

Reputation: 2588

select * from table order by case when name like "Teacher%" then 1 else 2 end,name 

Names starting with Teacher will be on top sorted alphabetically, then the rest. Example

Teacher
Teacher Aaron
Teacher Zed
Aaron
Zed

Upvotes: 0

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

Use FIELD function

SELECT * FROM table ORDER BY FIELD(`name`,'Teacher') ASC

Upvotes: 0

juergen d
juergen d

Reputation: 204766

select * from your_table
order by case when name = 'Teacher' then 1 else 2 end,
         name 

and for MySQL the following works since it returns 0 for false and 1 for true

select * from your_table
order by name <> 'Teacher',
         name 

Upvotes: 11

Related Questions