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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With