snippetsqlMajor
Sort by match of LIKE
Viewed 0 times
sortmatchlike
Problem
I wondering how I can implement SQL to get results sorted by best match of a like predicate. I have 100K articles in the database and when user call some items by part of name. I want to show the results ordered by the best match of asked query.
I'll try to describe that by pseudo code
I'll try to describe that by pseudo code
select
*
from
articles
where item_nale like '%'+@user_input +'%'
order by "BEST MATCH"Solution
Since all your matches have to match the LIKE pattern in order to be included, the simple thing to do is assume that shorter values for the column you're matching are "better" matches, as they're closer to the exact value of the pattern.
Alternatively, you could assume that values in which the match pattern appear earlier are "better" matches.
Or you could combine the two; look for earliest matches first, and within those, prefer shorter values.
It's not as sophisticated as what full-text indexing does, and it only accounts for matching on a single column, but it gives decent enough results.
ORDER BY LEN(item_nale) ASCAlternatively, you could assume that values in which the match pattern appear earlier are "better" matches.
ORDER BY PATINDEX('%' + @user_input + '%', item_nale) ASCOr you could combine the two; look for earliest matches first, and within those, prefer shorter values.
ORDER BY PATINDEX('%' + @user_input + '%', item_nale) ASC, LEN(item_nale) ASCIt's not as sophisticated as what full-text indexing does, and it only accounts for matching on a single column, but it gives decent enough results.
Code Snippets
ORDER BY LEN(item_nale) ASCORDER BY PATINDEX('%' + @user_input + '%', item_nale) ASCORDER BY PATINDEX('%' + @user_input + '%', item_nale) ASC, LEN(item_nale) ASCContext
StackExchange Database Administrators Q#8752, answer score: 25
Revisions (0)
No revisions yet.