## Levenshtein distance

The Levenshtein distance between two words is the minimum number of single-character edits (insertion, deletion, substitution) required to change one word into the other. – Wikipedia

To implement in MySQL, use the following function – if using phpmyadmin you will need to set a different delimiter such as ‘$’ instead of ‘;’ to create this function.

```
CREATE FUNCTION levenshtein( s1 VARCHAR(255), s2 VARCHAR(255) )
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE s1
```*len, s2*len, i, j, c, c*temp, cost INT;
DECLARE s1*char CHAR;
-- max strlen=255
DECLARE cv0, cv1 VARBINARY(256);
SET s1*len = CHAR*LENGTH(s1), s2*len = CHAR*LENGTH(s2), cv1 = 0x00, j = 1, i = 1, c = 0;
IF s1 = s2 THEN
RETURN 0;
ELSEIF s1*len = 0 THEN
RETURN s2*len;
ELSEIF s2*len = 0 THEN
RETURN s1*len;
ELSE
WHILE j <= s2*len DO
SET cv1 = CONCAT(cv1, UNHEX(HEX(j))), j = j + 1;
END WHILE;
WHILE i <= s1*len DO
SET s1*char = SUBSTRING(s1, i, 1), c = i, cv0 = UNHEX(HEX(i)), j = 1;
WHILE j <= s2*len DO
SET c = c + 1;
IF s1*char = SUBSTRING(s2, j, 1) THEN*

SET cost = 0; ELSE SET cost = 1;
END IF;
SET ctemp = CONV(HEX(SUBSTRING(cv1, j, 1)), 16, 10) + cost;
IF c > c*temp THEN SET c = c*temp; END IF;
SET c*temp = CONV(HEX(SUBSTRING(cv1, j+1, 1)), 16, 10) + 1;
IF c > c*temp THEN

SET c = c_temp;

END IF;
SET cv0 = CONCAT(cv0, UNHEX(HEX(c))), j = j + 1;
END WHILE;
SET cv1 = cv0, i = i + 1;
END WHILE;
END IF;
RETURN c;
END;

The following is example usage – it returns the name column ordered by the Levenshtein distance – the lowest number is the closest match.

```
SELECT name, LEVENSHTEIN(name, 'string') AS distance
FROM table ORDER BY distance ASC
```