Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order sql results starting with a certain string

I'm new to SQL and I really need your help, thank you for advance :)

I's using SQL to select a column (animal_name) whose contents contain a certain string (such as 'cat') from a table (animal), sample results:

mycat, hercat, catKitty, catLili, acata, bcatb

Now I want the results first display strings that start with 'cat', then display the remaining strings ASC, sample results I want to have:

catKitty, catLili, acata, bcatb, hercat, mycat

Now I just know how to use LIKE to select results containing 'cat':

select animal_name from animal where animal_name like '%cat%';

But I don't know how to order by the results. Can you give some suggestions? Thanks again :)

like image 624
Rixin Avatar asked Apr 10 '14 07:04

Rixin


1 Answers

select animal_name 
from animal 
where animal_name like '%cat%' --test if name contains cat
order by
 case when animal_name like 'cat%' then 0 else 1 end, -- order with name starting with cat first
 animal_name -- then by name

see SqlFiddle

like image 105
Raphaël Althaus Avatar answered Oct 14 '22 05:10

Raphaël Althaus