The naive way of doing this that comes to mind would be:
SELECT name, lev FROM
(SELECT name, levenshtein(name, *parameter*) as lev FROM my_table)
WHERE
lev = (SELECT MIN(lev) FROM
(SELECT name, levenshtein(name, *parameter*) as lev FROM my_table ));
However the "(SELECT name, levenshtein(name, parameter) as lev FROM my_table)" subquery, which is very expensive (huge table) is repeated twice which seems horribly inefficient.
I somehow though you could write :
SELECT name, lev FROM
(SELECT name, levenshtein(name, *parameter*) as lev FROM my_table) as my_temp_table
WHERE
lev = (SELECT MIN(lev) FROM my_temp_table);
But it doesn't seem to work.
Is there a clean way to optimize that query for speed? Did I miss something obvious?
Do I have to rely on temporary tables? (trying to avoid it due to the overhead/complexity as they don't seem appropriate for very frequent/concurrent queries)
Any input from SQL ninjas would be greatly appreciated ;)