22

I'm using MySQL 5.5 so that's why I can't use FULLTEXT search so please don't suggest it.

What I wanted to do is if user I have 5 records for example :

Amitesh
Ami
Amit
Abhi
Arun

and if someone searches for Ami then it should returns Ami first as exact match then Amit & Amitesh

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Mohit Bumb
  • 2,466
  • 5
  • 33
  • 52

3 Answers3

34

You can do:

select *
from table t
where col like '%Ami%'
order by (col = 'Ami') desc, length(col);
Railslide
  • 5,344
  • 2
  • 27
  • 34
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
5
SELECT *
FROM table t
WHERE col LIKE '%Ami%'
ORDER BY INSTR(col,'Ami') asc, col asc;
Brendan
  • 908
  • 2
  • 15
  • 30
  • Should be a _DESC_ on the first **Order By** to make it work as OP wanted: `ORDER BY INSTR(col, 'Ami') DESC, col ASC`. That said, thanks! This works as a charm in Doctrine/Symfony (with Doctrine extensions enabled) while the selected answer breaks because of the `=` sign – Erdal G. Nov 13 '20 at 13:41
1

More accurate output can be found using like in order by.

SELECT * FROM `table_name` WHERE col LIKE '%ami%' order by (col LIKE 'ami%') desc;