Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific ordering SQL Command

Tags:

sql

mysql

Say I have a table similar to:

ID    Name
1     Test
2     Contest
3     Fittest
4     Testament

Is there a MySQL query I could use with ordering to allow it to display a specific word first?

For example, users are searching for the word "Test". I have a statement similar to "SELECT * FROM table WHERE NAME LIKE '%Test%'". Could I display results to show things that START with Test begin first followed by everything else, while everything is still in alphabetical order.

So output would be:

Test
Testament
Contested
Fittest

Thanks.

like image 210
pyius Avatar asked Aug 03 '26 18:08

pyius


1 Answers

This will put your words that begin with Test at the top, and sort those words plus the remainder of the list in alphabetical order..

SELECT * FROM mytable 
ORDER BY CASE WHEN name LIKE 'test%' THEN 0 ELSE 1 END ASC, name ASC
like image 185
CResults Avatar answered Aug 06 '26 09:08

CResults