0

I have a query that gets information using the LIKE

SELECT * FROM table WHERE column LIKE '%$search%'

Now if i search for "Hello there" it will return something like

Oh hello there
Hello there
Hello there how are you

But i want to sort it by exact match first so it should be like

Hello there
Hello there how are you
Oh hello there

With the exact match on top and the exact match at the start of the sentence after that

0

3 Answers 3

13

try this

    SELECT * FROM table1 WHERE column LIKE '%$search%'
    order by case when column like '$search%'  then 1        //hello in begining
                  when column like '%$search%' then 2        //hello in middle
                  when column like '%$search'  then 3 end    //hello in end

watch demo here

7
  • Doesn't return anything, hmm Jul 20, 2013 at 14:28
  • doesnt return anything? check my answer and look demo
    – echo_Me
    Jul 20, 2013 at 14:31
  • I did, i changed the hello to my variable and changed the column name and it won't return anything Jul 20, 2013 at 14:33
  • be sure to change $search in all like , because it should work perfect or you made something wrong.
    – echo_Me
    Jul 20, 2013 at 14:36
  • Great works thank you Jul 20, 2013 at 14:39
7

Use INSTR to order the result by the position of the search string in the column:;

SELECT * FROM table 
WHERE column LIKE '%$search%'
order by INSTR(column, '$search')
2
  • Great thanks, is there a way i can have the results after the exact match ordered by if the string begins the sentence, like "hello there you" would be above "you hello there" Jul 20, 2013 at 14:25
  • @user2458791: You can use INSTR(). See my update.
    – juergen d
    Jul 20, 2013 at 19:35
-2
SELECT * FROM table WHERE column LIKE '%$search%' ORDER BY column
1
  • No gives me same output Jul 20, 2013 at 14:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.