Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL order by "best match"

People also ask

What is sort by best match?

Users who sort by "Best Match" are typically clicking through citations on the first page of retrieval; therefore, we limit the list of best matching results to 10,000 citations when applicable.

How do I use ORDER BY like Operator?

When you use LIKE operator to search and fetch the matched results from the database, the records are selected based on their entry. On another hand, the ORDER BY keyword allows you to sort the result-set in ascending or descending order based on a specific column.

Does order matter in mysql?

So the order of columns in a multi-column index definitely matters. One type of query may need a certain column order for the index. If you have several types of queries, you might need several indexes to help them, with columns in different orders.

Can we use ORDER BY before group by in mysql?

This is not permitted if the ONLY_FULL_GROUP_BY SQL_MODE is used." So you can't guarantee the order. You however use a function such as MAX(info) to get a specific value.


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.


Try this way:

SELECT word 
FROM words 
WHERE word LIKE '%searchstring%' 
ORDER BY CASE WHEN word = 'searchstring' THEN 0  
              WHEN word LIKE 'searchstring%' THEN 1  
              WHEN word LIKE '%searchstring%' THEN 2  
              WHEN word LIKE '%searchstring' THEN 3  
              ELSE 4
         END, word ASC

You could use the INSTR function to return the starting position of the search string within the word,

 ORDER BY INSTR(word,searchstring)

To make the resultset more deterministic when the searchstring appears in the same position in two different words, add a second expression to the ORDER BY:

 ORDER BY INSTR(word,searchstring), word

(For example, searchstring hab appears in second position of both chablis and shabby)