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
but I'd like it this way:
or at least this way:
Would be great if anyone could help me out with this!
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.