CobaltBabyBear
CobaltBabyBear

Reputation: 2218

MySQL: Statement with 'LIKE' order by degree of resemblance

I have a simple MySQL query that runs on a large set of keywords for the purpose of searching by keyword.

SELECT * from table_name WHERE column_name LIKE '%keyword%'

How can I order the resultant set by degree of resemblance (in this case the string length) with the search keyword of inter? For example, the resultant set is something like this.

international
internal
internet
interval
intern
internee
internship

Is it possible with SQL alone or do I need to do it on the programming level?

Upvotes: 0

Views: 321

Answers (1)

Taryn
Taryn

Reputation: 247880

You can order the data by the string length using order by length(column_name) desc:

SELECT * 
from table_name 
WHERE column_name LIKE '%inter%'
order by length(column_name) desc

See SQL Fiddle with Demo. I chose descending order but you can remove the desc to order by ascending length.

Upvotes: 2

Related Questions