24x7Code 24x7Code - 5 months ago 11
MySQL Question

How to sort result based on matching

I have this problem with this site where user can search by stock symbol or stock name

If it matchs exact with a symbol, results need to be displayed first then the remaining.

Table structure is like this :

pk | symbol | stockname


Example of scenario :

symbol = eta


stock name = energy transfer equity


This result with exact match with
ete
but it got buried in search results.

Could you help me solving this ?

Answer

You can use e.g.

select symbol, stockname
from yourtable
where ...
order by (symbol = 'eta') desc

(symbol = 'eta') will have the value 1 when it matches, 0 if it doesn't match.