MySQL order by "best match"

eevaa picture eevaa · Sep 10, 2013 · Viewed 27.2k times · Source

I have a table that contains words and an input field to search that table using a live search. Currently, I use the following query to search the table:

SELECT word FROM words WHERE word LIKE '%searchstring%' ORDER BY word ASC

Is there a way to order the results so that the ones where the string is found at the beginning of the word come first and those where the string appears later in the word come last?

An example: searching for 'hab' currently returns

  1. a lphabet
  2. h abit
  3. r ehab

but I'd like it this way:

  1. hab it (first because 'hab' is the beginning)
  2. alp hab et (second because 'hab' is in the middle of the word)
  3. re hab (last because 'hab' is at the end of the word)

or at least this way:

  1. hab it (first because 'hab' is the beginning)
  2. re hab (second because 'hab' starts at the third letter)
  3. alp hab et (last because 'hab' starts latest, at the fourth letter)

Would be great if anyone could help me out with this!

Answer

Ed Gibbs picture Ed Gibbs · Sep 10, 2013

To do it the first way (starts word, in the middle of the word, ends word), try something like this:

SELECT word
FROM words
WHERE word LIKE '%searchstring%'
ORDER BY
  CASE
    WHEN word LIKE 'searchstring%' THEN 1
    WHEN word LIKE '%searchstring' THEN 3
    ELSE 2
  END

To do it the second way (position of the matched string), use the LOCATE function:

SELECT word
FROM words
WHERE word LIKE '%searchstring%'
ORDER BY LOCATE('searchstring', word)

You may also want a tie-breaker in case, for example, more than one word starts with hab. To do that, I'd suggest:

SELECT word
FROM words
WHERE word LIKE '%searchstring%'
ORDER BY <whatever>, word

In the case of multiple words starting with hab, the words starting with hab will be grouped together and sorted alphabetically.