Question

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 :)

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top